memory allocation for array of pointers

前端 未结 4 803
梦如初夏
梦如初夏 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:43

    Emphisizing what Jack said in in the end: his code works only if the array is declared as a pointer-of-pointers by using **.

    When the array is declared as

    char *names[5];
    

    I guess the right way of allocating memory is almost as Ak1to did, but multiplying by the wanted size of the string of chars:

    char *names[5];
    for(i=0;i<5;i++)
    {
      names[i]=(char *)malloc(sizeof(char)*80);
    }
    

    else the compiler throws an error about incompatible types.

提交回复
热议问题