Getting the size of a malloc only with the returned pointer

后端 未结 5 408
被撕碎了的回忆
被撕碎了的回忆 2020-11-29 11:42

I want to be able to vary the size of my array so I create one this way:

int* array;
array = malloc(sizeof(int)*10);//10 integer elements

I

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 12:16

    Use a pointer-to-array type rather than a pointer-to-element type:

    int (*parray)[10] = malloc(sizeof *parray);
    

    Then sizeof *parray gives you the desired answer, but you need to access the array using the * operator, as in (*parray)[i] (or equivalently albeit confusingly, parray[0][i]). Note that in modern C, 10 can be replaced with a variable.

提交回复
热议问题