maknel
maknel

Reputation: 309

Modifying a structure member with pointers in C

I'm trying to assign a value to a member of a structure in a very roundabout way. Here are the steps I'm taking:

  1. In main, create an array of structure pointers.
  2. (Still in main) Pass a pointer to that array to a function.
  3. Inside the function, create a structure and add a pointer to it to the array.
  4. (Still inside function) Assign a value to a member of the structure that was just created.

I'm very new to C, so I don't have a very good understanding of pointers. I thought that this process would allow me to see the value that was assigned from main, but when I print it it appears to be empty. What am I doing wrong (barring the obvious - I'm making this way too complicated)? Here's the code:

#include <stdio.h>
#include <string.h>

struct MyStruct {
    char name[9];
};

void give_name(struct MyStruct ** structlist_ptr) {
    struct MyStruct new_struct;
    structlist_ptr[0] = &new_struct;
    strcpy(structlist_ptr[0]->name, "confused");
}

int main(void) {
    struct MyStruct * struct_list[1];

    give_name(struct_list);
    printf("%s\n", struct_list[0]->name); /* Appears to print random characters */

    return 0;
}

Upvotes: 2

Views: 112

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409166

The major problem is this assignment:

structlist_ptr[0] = &new_struct;

With that you make *structlist_ptr (the usual way to use "reference" pointers) point to the local variable new_struct.

Once the function returns, the life-time of the local variables will end as they go out of scope. They will, in a manner of speaking, cease to exist. That leaves you with a stray and invalid pointer. Attempting to dereference it will lead to undefined behavior.

Upvotes: 8

Related Questions