Assigning memory to double pointer?

后端 未结 7 880
广开言路
广开言路 2020-12-04 16:18

I am having trouble understanding how to assign memory to a double pointer. I want to read an array of strings and store it.

    char **ptr;
    fp = fopen(\         


        
7条回答
  •  有刺的猬
    2020-12-04 16:59

    Adding to Pent's answer, as he correctly pointed out, you will not be able to use this double pointer once the function returns, because it will point to a memory location on the function's activation record on stack which is now obsolete (once the function has returned). If you want to use this double pointer after the function has returned, you may do this:

    char * realptr = (char *) malloc(1234);
    char ** ptr = (char **) malloc(sizeof(char *));
    *ptr = realptr;
    return ptr;
    

    The return type of the function must obviously be char ** for this.

提交回复
热议问题