【问题标题】:Adding structs to an array and changing their attributes将结构添加到数组并更改其属性
【发布时间】:2018-12-05 19:26:02
【问题描述】:
    int numOfProcesses = 0;
printf("How many processes would you like to enter: ");
scanf("%d",&numOfProcesses);
struct process p[numOfProcesses];
int counter = 1;
// This is the quantum printf(argv[1]);
// This is the type to run printf(argv[2]);
if(argv[2] = "FCFS"){
  while(counter < numOfProcesses){
    int temp;
    p[counter];
    printf("For process %d: \n",counter);
    printf("Enter the pid: ");
    scanf("%d", p[counter].pid);
    printf("Enter the burst time: ");
    scanf("%d",p[counter].burstTime);
    printf("Enter the arrival time: ");
    scanf("%d",p[counter].arrivalTime);

    counter++;
  }

我试图让我的代码保存一个结构数组,并允许我编辑数组中结构的属性,但一切都会导致段错误。我在做什么?

【问题讨论】:

  • scanf("%d", p[counter].pid); -> scanf("%d", &amp;p[counter].pid);。接下来的两个也一样。
  • 打开编译器警告。
  • if(argv[2] = "FCFS"){ -->> if(!strcmp(argv[2] , "FCFS")){
  • p[counter]; 什么都不做。
  • 你从 1 开始,但数组从 0 开始。

标签: c arrays struct


【解决方案1】:

我在代码中看到多个问题:

  1. if(argv[2] = "FCFS")

A.我认为目标是比较事物。它必须是“==”而不是“=”。但这同样不适用于字符串

B.对于字符串,你必须写成 if(!strcmp(argv[2], "FCFS")

  1. 行 p[counter];不需要。它没有任何动作。

  2. 计数器必须初始化为 0 而不是 1

  3. 我不确定 struct process 的成员,但我假设它们都是整数。在scanf中你必须传递成员的地址

scanf("%d", &p[counter].pid);

scanf("%d", &p[counter].burstTime);

scanf("%d", &p[counter].arrivalTime);

如果它们是指向整数的指针,那么也会发生分段错误,因为它们没有在代码中的任何地方初始化

【讨论】:

    猜你喜欢
    • 2017-01-13
    • 1970-01-01
    • 2020-02-01
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 2018-01-23
    • 2020-10-31
    • 1970-01-01
    相关资源
    最近更新 更多