c - 尝试将内存分配给单独声明的指针变量时出错

标签 c pointers malloc

<分区>

我已经通过以下方式声明了一个 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

关于c - 尝试将内存分配给单独声明的指针变量时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34983233/

相关文章:

c - GSL 特征值代码

c - c中的分配存储和二进制fwrite短裤

c - 分段故障。错误退出c程序

c - c中的malloc函数?

c - 使用新文件扩展名写入文本文件

c - 使用辅助结构在 O(N) 时间内查找数组是否有重复项

java - 处理与 JNI 的关联

两个程序中指针的地址可以相等吗?

c - 数组地址在 C 中不正确递增

c - 求 C 中两个值之间的步长