memory allocation for array of pointers

前端 未结 4 805
梦如初夏
梦如初夏 2021-02-10 01:45

I need to allocate memory for a pointer which needs to be used as a 2d array.I know how to allocate memory for char pointers and int pointers I am confused how memory is allocat

4条回答
  •  温柔的废话
    2021-02-10 02:40

    No, this is not because you are allocating the array assuming a dimension of just 1 element of primitive type char (which is 1 byte).

    I'm assuming you want to allocate 5 pointers to strings inside names, but just pointers.

    You should allocate it according to the size of the pointer multiplied by the number of elements:

    char **names = malloc(sizeof(char*)*5);
    

    You don't need to allocate them one by one with a loop. Note that you need to specify that it is a pointer-of-pointers by using **

提交回复
热议问题