在函数

时间:2017-01-12 14:35:19

标签: c pointers struct parameter-passing

我无法理解我的c实现有什么问题:在函数内动态分配一个struct数组,以便在其他函数中使用。

问题是我的.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;
}

Warrnings:

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=]|

使用+ i而不是[i]不会改变任何东西。我知道&amp;(* 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);

作品。

1 个答案:

答案 0 :(得分:1)

这里

*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,而其他两个地方需要scanf,因为另外两个是数组。

在评论中提及 @unwind scanf("%d",&(*n)); 错误

scanf("%d", n);

应该是

if (scanf("%d", n) != 1)
{
    // Add error handling here
    ....
}

然后你还应检查返回值,如

{{1}}
相关问题