c - c 中 malloc 与许多结构的用法

标签 c struct malloc

我尝试用我的结构存储很多东西。这些变量似乎存储在“do-while”中,但是当我尝试访问在 do-while 之后存储的元素时,该元素消失了。 我做错了什么?

#include <stdio.h>
#include <stdlib.h>

struct Sauto {
int part;

};

int main() {
int i=0;
struct Sauto *car;

do {
    car = malloc(sizeof(struct Sauto)+(sizeof(struct Sauto)*i));
    struct Sauto car[i];

    printf("part%i:", i);
    scanf("%i", &car[i].part);
    printf("part%i is %i\n", i, car[i].part);
    i++;
} while (i<3);
printf("part 0 is %i\n", car[0].part);
return 0;
}

最佳答案

您重新声明了一个同名“car”的变量。删除do-while循环中的声明。

关于c - c 中 malloc 与许多结构的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35538300/

相关文章:

c - 在 C 中,如何将全局变量的范围限制在声明它的文件中?

objective-c - 如何将 RGB 整数转换为相应的 RGB 元组 (R,G,B)?

c - 如何解决以下函数中的内存分配问题? (分配)

c - 如何分析 C 语言中简单算法的效率

php - 从 PHP 写入 C 程序的 STDIN

c - 在头文件的声明中定义结构的值

c++ - 如何使用结构作为条件的操作数?

使用宏时 C 结构数组初始化问题

c - 在 malloc 期间接收信号

c - 使用断言处理错误检查