C - Does freeing an array of pointers also free what they're pointing to?

前端 未结 3 2232
深忆病人
深忆病人 2020-12-08 17:53

Say I have an array of pointers to structs that contain a string each and so for something like this:

printf(\"%s\\n\", array[0]);

The outp

3条回答
  •  Happy的楠姐
    2020-12-08 18:31

    If I perform a free(array) will this free what array[0] is pointing to? ("Hello.").

    No they don't get freed automatically, but depending on how you allocated each of them, there might be no need to free them actually. You would only need to free them if they point to memory which was returned by malloc and similar allocation functions.

    Say you have array of pointers to string array

    char * array[2];
    array[0] = "Some text"; // You would not need to free this
    array[1] = malloc(LENGTH); // This one you would have to free
    

    Note in this case you don't need to free the array itself. Only the element with index 1.

提交回复
热议问题