我无法理解我的c实现的问题所在:在函数内部动态分配结构数组,以在其他函数中使用。
问题是我的.exe在读取第一个struct(正确读取)后停止工作。
结构:
struct student
{
char name1[30], name2[30];
float grade;
};
功能:
void read(int *n, struct student **a)
{
if(scanf(" %d", n) == 1)
{
int i;
*a=(struct student*)malloc((*n)*sizeof(struct student*));
for(i=0; i<*n; i++)
scanf("%29s %29s %f",(*a)[i].name1, (*a)[i].name2, &(*a)[i].grade);
//it stops working right after this line is executed
}
}
主要:
int main()
{
int n;
struct student *a;
read(&n, &a);
return 0;
}
警告:
format '%s' expects argument of type 'char *', but argument 2 has type 'char (*)[30]' [-Wformat=]|
format '%s' expects argument of type 'char *', but argument 3 has type 'char (*)[30]' [-Wformat=]|
使用a + i代替a [i]不会改变任何东西。我知道&(* a)的意思是a,但我想让所有内容尽可能清楚。我觉得动态分配存在明显的问题,这是我所缺少的。我在这里读了很多问题,但似乎没有什么可以解决我的问题。谢谢你的时间!
编辑1:我将代码更改为建议:
scanf(“%29s%29s%f”,a [i] .name1,a [i] .name2,a [i] .grade);
现在我得到下面的错误。
错误:
错误:请求成员“ name1”的不是结构或联合
编辑2:因此,该行:
scanf("%29s %29s %f",*a[i].name1, *a[i].name2, *a[i].grade);
给出错误:
在非结构或联合中要求成员“ name1”
和线:
scanf("%29s %29s %f",(*a)[i].name1, (*a)[i].name2, (*a)[i].grade);
崩溃。
编辑3:
scanf("%29s %29s %f", (*a)[i].name1, (*a)[i].name2, &(*a)[i].grade);
作品。
最佳答案
这里
*a=(struct student*)malloc((*n)*sizeof(struct student*));
^^^^^
您为
*n
指向struct student
的指针分配空间,但看来您确实想为*n struct student
分配空间。看来您想要:
*a=malloc((*n)*sizeof(struct student));
另请注意,
*a[i]
与*(a[i])
相同,但您可能需要(*a)[i]
。因此,您需要类似:scanf("%29s %29s %f", (*a)[i].name1, (*a)[i].name2, &(*a)[i].grade);
请注意,您需要在
&
前面的(*a)[i].grade
而不是其他两个地方,因为另外两个是数组。正如@unwind在评论中提到的:
scanf
是错误的这个
scanf("%d",&(*n));
应该
scanf("%d", n);
然后您还应该检查返回值,例如
if (scanf("%d", n) != 1)
{
// Add error handling here
....
}
关于c - 在函数内部动态分配结构数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41615806/