Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am having a problem initializing an array of structs. I'm not sure if I am doing it right because I get "initialization from incompatible pointer type" & "assignment from incompatible pointer type". I added in the code where I get these warnings, and when I try to print the data from the struct I just get garbage such as @@###

typedef struct
{
    char* firstName;
    char* lastName;
    int day;
    int month;
    int year;

}student;

//initialize array

    student** students = malloc(sizeof(student));
    int x;
    for(x = 0; x < numStudents; x++)
    {
        //here I get: "assignment from incompatible pointer type" 
        students[x] = (struct student*)malloc(sizeof(student));
    }

    int arrayIndex = 0;

//add struct

 //create student struct
        //here I get: "initialization from incompatible pointer type"
        student* newStudent = {"john", "smith", 1, 12, 1983};

        //add it to the array
        students[arrayIndex] = newStudent;
        arrayIndex++;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
631 views
Welcome To Ask or Share your Answers For Others

1 Answer

This is incorrect:

student** students = malloc(sizeof(student));

You do not want a **. You want a * and enough space for how ever many students you need

student *students = malloc(numStudents * sizeof *students); // or sizeof (student)
for (x = 0; x < numStudents; x++)
{
    students[x].firstName = "John"; /* or malloc and strcpy */
    students[x].lastName = "Smith"; /* or malloc and strcpy */
    students[x].day = 1;
    students[x].month = 12;
    students[x].year = 1983;
}

If you still want to use the code in your "//add struct" section, you'll need to change the line:

student* newStudent = {"john", "smith", 1, 12, 1983};

to

student newStudent = {"john", "smith", 1, 12, 1983};

You were getting "initialization from incompatible pointer type" because you were attempting to initialize a pointer to student with an object of type student.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...