[英]Dynamically allocating an array of struct inside a function
我無法理解我的 c 實現有什么問題:在函數內動態分配結構數組以在其他函數中使用。
問題是我的 .exe 在讀取第一個結構(正確讀取)后停止工作。
結構:
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*));
^^^^^
您為指向struct student
*n
指針分配了空間,但似乎您確實想為*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
....
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.