How do I use a structure?

前端 未结 3 660
执念已碎
执念已碎 2020-12-12 07:33

Ok firstly I\'ll explain my assignment. For this assignment I have to use dynamic memory allocation which I am having no problems with. What I am having a problem with is fi

3条回答
  •  半阙折子戏
    2020-12-12 07:57

    The first problem is that you have variable names the same as the name of the type. Although you can have that in C to a certain extent, like:

    typedef int x;
    x foo (x x)
    {
      return x;
    }
    

    It might be a good idea not to do this for the readability purposes. So in your case you have:

    int * studentData= NULL;
    int * studentDataType= NULL;
    

    which is a variable name, then you have:

    struct studentDataType ...
    

    which is a name of the type (should be used as struct studentDataType, not without struct as you do); finally

    studentDataType *studentData = ...
    

    is treated by the compiler as an operation on two variables, not a type declaration as you would expect. So your memory allocation needs to be:

    struct studentDataType *studentData = malloc(numberOfStudents *sizeof(struct studentData));
    

    Which brings a problem that you redefine studentData, which you declared in the beginning of the program, and "numberOfStudents" is not defined, probably you wanted to write "students" instead.

    As for the reading data with scanf, see the previous comment.

提交回复
热议问题