Allocate space for struct pointer in subfunction

前端 未结 4 1730
死守一世寂寞
死守一世寂寞 2020-12-22 03:40

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:

#i         


        
4条回答
  •  太阳男子
    2020-12-22 04:03

    In your example:

    void allocate_and_initialize(struct _struct *s)
    {
        s = calloc(sizeof(struct _struct), 1);
        s->str = calloc(sizeof(char), 12);
        strcpy(s->str, "hello world");
    }
    

    Assigning to s here doesn't change s in the caller. Why not return it instead?

    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;
    }
    

    and use it thus:

    struct _struct *s;
    s = allocate_and_initialize();
    /* use s... */
    free(s); /* don't forget to free the memory when you're done */
    

提交回复
热议问题