Reputation: 309
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:
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
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