Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c - Allocate space for struct pointer in subfunction

How can I allocate memory for a struct pointer and assign value to it's member in a subfunction?

The following code will compile but not execute:

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

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
", s->str);

    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are passing s by value. The value of s is unchanged in main after the call to allocate_and_initialize

To fix this you must somehow ensure that the s in main points to the memory chunk allocated by the function. This can be done by passing the address of s to the function:

// 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
", s->str);

        return 0;
}

Alternatively you can return the address of the chunk allocated in the function back and assign it to s in main as suggested in other answer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...