在子函数中为struct指针分配空间
如何为结构指针分配内存并为其子function中的成员赋值?
以下代码将编译但不执行:
#include #include #include struct _struct {char *str;}; void allocate_and_initialize(struct _struct *s) { s = calloc(sizeof(struct _struct), 1); s->str = calloc(sizeof(char), 12); strcpy(s->str, "hello world"); } int main(void) { struct _struct *s; allocate_and_initialize(s); printf("%s\n", s->str); return 0; }
你是按价值传递s
。 在调用allocate_and_initialize
之后, s
的值在main中保持不变
要解决此问题,您必须以某种方式确保s
in main指向函数分配的内存块。 这可以通过将s
的地址传递给函数来完成:
// s is now pointer to a pointer to struct. void allocate_and_initialize(struct _struct **s) { *s = calloc(sizeof(struct _struct), 1); (*s)->str = calloc(sizeof(char), 12); strcpy((*s)->str, "hello world"); } int main(void) { struct _struct *s = NULL; // good practice to make it null ptr. allocate_and_initialize(&s); // pass address of s. printf("%s\n", s->str); return 0; }
或者,您可以返回函数中分配的块的地址,并将其分配给main中的s
,如其他答案中所建议的那样。
在你的例子中:
void allocate_and_initialize(struct _struct *s) { s = calloc(sizeof(struct _struct), 1); s->str = calloc(sizeof(char), 12); strcpy(s->str, "hello world"); }
在此处分配s
不会更改呼叫者中的s
。 为什么不回来呢?
struct _struct *allocate_and_initialize(void) { struct _struct *s; s = calloc(sizeof *s, 1); s->str = calloc(1, 12); /* sizeof(char) is always 1 */ strcpy(s->str, "hello world"); return s; }
并使用它:
struct _struct *s; s = allocate_and_initialize(); /* use s... */ free(s); /* don't forget to free the memory when you're done */
你必须改变你的代码:
#include #include #include struct _struct {char *str;}; void allocate_and_initialize(struct _struct **s) { *s = (_struct*)calloc(sizeof(struct _struct), 1); (*s)->str = (char*)calloc(sizeof(char), 12); strcpy((*s)->str, "hello world"); } int main(void) { struct _struct *s; allocate_and_initialize(&s); printf("%s\n", s->str); return 0; }
原因是,您更改了指针的地址,而不是指针的“内容”。 所以,如果你用c编码,你必须使用“双”指针。 如果使用c ++编写代码,则可以使用引用。
您可以创建struct对象,然后将其地址传递给子函数,然后通过创建指针在子函数中指定值。 确切的代码是,
#include #include #include struct _struct {char *str;}; void allocate_and_initialize(struct _struct *s) { s -> str = malloc(12); strcpy(s->str, "hello world"); } void main(void) { struct _struct _struct; allocate_and_initialize(&_struct); printf("%s\n", _struct.str); }