How do I use a structure?

前端 未结 3 659
执念已碎
执念已碎 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:47

    You're redefining studentData

    int * studentData= NULL;

    then later

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

    You should declare the studentDataType struct first (outside of main() ) then use it in your original declaration

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-12 08:03

    To see the task it is better at least for the first time to write some block-scheme of what you have to do in a program. In your case:

    1. Read data from user (each structure).
    2. Increase array size, add new structure.
    3. Loop 1-2 until input user finish adding new people (needs some condition here to finish).
    4. Find necessary structure and print it.

    So the first step is to read information from user. You can use scanf(): In the simplest way you can do that step-by-step for each field:

    #include <stdio.h>
    ...
    int value;
    scanf("%d", &value);
    ...
    

    In case of success this function should return number of items it reads (1 in your case). For phone you should use scanf("%ld", &phone).

    To resize array use function realloc() (#include :

    realloc(&ptr_to_array, new_size);
    

    Each elements of the array is a pointer to structure "student". Next steps are similar.

    0 讨论(0)
提交回复
热议问题