我已经通过以下方式声明了一个 char 指针:
School *student[10];
for(i=0;i<10;i++){
*student[i] = malloc(sizeof(Student)); <--- Error points here
}
我得到的错误是:
incompatible types when assigning to type 'struct Student' from type 'void*'
有人知道我为什么会收到此错误吗?
但是,如果我要在同一行中分配内存,那怎么会和星一样呢?例如:Student *name = malloc(sizeof(Student));
为什么这样做有效?我有点困惑
*student[i] = malloc(sizeof(School));
应该是 student[i] = malloc(sizeof(School));
students
是指向 School
类型结构的指针数组。所以你需要为该数组中的每个指针分配。当您编写 *student[i]
- 您正在取消引用指针 i
而不是为其分配内存。
正如 NicolasMiari 指出的那样,sizeof
运算符必须应用于 School
而不是 student
。
But how come if I were to allocate memory in the same line it would be with the star. For example: Student *name = malloc(sizeof(Student)); Why does this work? Im a bit confused
这是不一样的。当您编写 Student *name = malloc(sizeof(Student));
时,您同时声明了一个指针并使用 malloc
初始化它。您可以像这样在一行中执行这两个步骤。或者,您先声明它,然后在不同的行中用 malloc
分配它 - 在这种情况下,您必须删除星号。
你可能想引用这个问题 pointer initialization and pointer assignment 。