Allocate space for struct pointer in subfunction

前端 未结 4 1729
死守一世寂寞
死守一世寂寞 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 03:56

    you must change your code like that:

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

    The reason is, that you change the adress of the pointer, but not the "content" of the pointer. So, if you code in c, you have to use a "double" pointer. If you code in c++ you can use a reference.

提交回复
热议问题