【发布时间】:2012-03-15 23:37:09
【问题描述】:
我是 C 新手,无法理解为什么 my_struct_ptr (main) 在以下示例中为 nil。如何将 my_structs 数组中结构的地址分配给 get_my_struct_by_name 函数中的 my_struct_ptr 指针?
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;
}
编辑:添加示例输出以希望对其他人有所帮助。感谢所有回复的人。这正是我正在寻找的帮助!
输出:
[prompt ~]$ ./test
works: b,b description,value 2
nil: (nil)
Segmentation fault
【问题讨论】:
-
你说的这个“nil”是什么? :-)
-
@Ed S. printf %p 说明符在 main 中生成“(nil)”而不是 my_struct_ptr 的地址。我更新了问题以帮助其他人澄清。谢谢
标签: c arrays pointers struct pass-by-reference