0

After defining the type student (which is a struct made of two arrays of characters and an int), I've created an array of pointers to student, which I need in order to modify its content inside of a series of functions.

int main(void) 
{
    student* students[NUMBER_OF_STUDENTS];

    strcpy(students[0]->name, "test");
    strcpy(students[0]->surname, "test");
    students[0]->grade = 18;

    return EXIT_SUCCESS;
}

My problem is that this simple piece of code returns -1 as exit status after running. Why is that?

3 Answers 3

3

The pointer students[0] is uninitialized. Dereferencing it results in undefined behavior.

Initialize it with the address of a valid object before attempting to access it.

student test;
students[0] = &test;

strcpy(students[0]->name, "test");
strcpy(students[0]->surname, "test");
students[0]->grade = 18;
Sign up to request clarification or add additional context in comments.

Comments

3

Because it is UB. You have only pointer without the actual structs allocated.

students[x] = malloc(sizeof(*students[0]));

or statically

student s;
students[x] = &s;

or

 students[x] = &(student){.name = "test", .surname ="test", .grade = 18};

Comments

1

The pointers are pointing to nowhere since you have not allocated any memory for them to point to.

int main(void) 
{
    student* students = (student*)malloc(sizeof(student)*[NUMBER_OF_STUDENTS]); \\malloc dynamically allocate heap memory during runtime

strcpy(students[0]->name, "test");
strcpy(students[0]->surname, "test");
students[0]->grade = 18;

return EXIT_SUCCESS;

}

*Note Edit by marko -- Strictly the pointers are pointing to whatever was last in the stack location or register holding it - it may be nothing, or something you actually care about. The joys of UB

1 Comment

Strictly the pointers are pointing to whatever was last in the stack location or register holding it - it may be nothing, or something you actually care about. The joys of UB

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.