#include <stdio.h>
#include <stdlib.h>
main()
{
typedef struct
{
int info;
struct strc* next_ptr;
}strc;
strc* strcVar[5];
strcVar = malloc(sizeof(strc) * 5);
strcVar[0]->info = 1;
printf(" All is well ");
}
答案 0 :(得分:2)
strcVar
是(本地)数组名称,您无法为其指定指针。你可能想要:
strc* strcVar;
... /* and later */
strcVar[0].info = 1;
也许你想要一个指向struct strc
的指针数组,然后Vaughn Cato的答案会有所帮助。
答案 1 :(得分:2)
这一行错误且不必要:
strcVar = malloc(sizeof(strc) * 5);
相反,您可以使用:
{
int i=0;
for (;i!=5; ++i) {
strcVar[i] = malloc(sizeof(strc));
}
}
答案 2 :(得分:2)
您无法从malloc
分配数组 - 它是一个或另一个。如果你声明了一个包含五个指针的数组,那么它们的内存已经被分配了。如果必须使用malloc
,请使用指向指针而不是数组的指针。否则,使用malloc
分配单个项目,而不是数组:
strc* strcVar[5];
strcVar[0] = malloc(sizeof(strc));
答案 3 :(得分:2)
更改
strc* strcVar[5];
到
strc* strcVar;
strcVar = malloc(sizeof(strc) * 5);
strcVar[0].info = 1;
或强>
更改
strc* strcVar[5];
strcVar = malloc(sizeof(strc) * 5);
strcVar[0]->info = 1;
到
strc strcVar[5];
strcVar[0].info = 1;
答案 4 :(得分:1)
修复代码:
#include<stdio.h>
#include<stdlib.h>
void main()
{
typedef struct
{
int info;
struct strc* next_ptr;
}strc;
strc* strcVar;
strcVar = malloc(sizeof(strc) * 5);
strcVar[0].info = 1;
printf(" All is well ");
}
答案 5 :(得分:0)
在任何数组中,基址是const指针。你无法改变它。
假设您有int [5];
这里是指向整个数组的基指针,不允许更改它。
这适用于所有阵列。