I am new to C and having trouble understanding why my_struct_ptr (main) is nil in the following example. How would I assign the address of a struct in the my_structs array to the my_struct_ptr pointer within the get_my_struct_by_name function?
struct my_struct { char *name; char *descr; char *value; } my_structs[3] = { {"a", "a description", "value 1"}, {"b", "b description", "value 2"}, {"c", "c description", "value 3"} }; int get_my_struct_by_name(char *name, struct my_struct *my_struct_ptr) { int i; for (i=0; i < (sizeof(my_structs)/sizeof(struct my_struct)); i++) { if (strcmp(name, my_structs[i].name) == 0) { my_struct_ptr = &my_structs[i]; printf("works: %s,%s,%s\n", my_struct_ptr->name, my_struct_ptr->descr, my_struct_ptr->value); return 0; } } return -1; } int main() { int res = 0; struct my_struct *my_struct_ptr; if (res = get_my_struct_by_name("b", my_struct_ptr)) return res; printf( "nil: %p\n", my_struct_ptr); printf("seg fault: %s,%s,%s\n", my_struct_ptr->name, my_struct_ptr->descr, my_struct_ptr->value); return res; } Edit: Adding example output to hopefully help others. Thank you to everyone who responded. This is exactly the help I was looking for!
Output:
[prompt ~]$ ./test works: b,b description,value 2 nil: (nil) Segmentation fault