【问题标题】:Can't assign values to array of structs ansi c无法为结构数组赋值
【发布时间】:2023-03-30 00:17:01
【问题描述】:

您好已经定义了这个 struct typdef:

typedef struct{
        int pid;
        int valor;
    }hijo;

但是在为其保留内存后,我迭代数组以将值分配给每个结构,但值未正确存储:

hijo *retorno;
retorno=malloc(processes*sizeof(hijo));

while (processes > 0) {
        pid = wait(&status);
        int valors = WEXITSTATUS(status);
        retorno[i].valor=valors;
        retorno[i].pid=pid;
        --processes;  // TODO(pts): Remove pid from the pids array.
    }

谢谢。

【问题讨论】:

  • ANSI-C 不是 C 标签所暗示的标准 C。说:你应该离开 1990 年代并使用现代 C。最好的标准 C 是 C11,但至少是 C99。
  • 你的意思是值没有正确存储?请发布 MCVE; stackoverflow.com/help/mcve

标签: arrays struct c89


【解决方案1】:

您需要初始化和递增i。否则,您将继续分配给相同的数组元素。

hijo *retorno;
retorno=malloc(processes*sizeof(hijo));
int i = 0;

while (processes > 0) {
    pid = wait(&status);
    int valors = WEXITSTATUS(status);
    retorno[i].valor=valors;
    retorno[i].pid=pid;
    --processes;  // TODO(pts): Remove pid from the pids array.
    i++;
}

或者,您可以将iprocesses 进行比较,而不是更新两个变量:

for (int i = 0; i < processes; i++) {
    pid = wait(&status);
    int valors = WEXITSTATUS(status);
    retorno[i].valor=valors;
    retorno[i].pid=pid;
}

【讨论】:

    【解决方案2】:

    使用此代码,您将减少 processes,并且您想为 retorno 分配值,我猜。 那么retorno[i] 应该是retorno[processes] 对吧?

    否则我不明白你想做什么。

    【讨论】:

    • 应该是retorno[processes-1] 以防止越界访问。
    • 这看起来更像是一条评论。答案不予置评。先找代表,这样你就可以写评论了。
    猜你喜欢
    • 1970-01-01
    • 2016-11-05
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多