使用malloc创建指向指针的指针

1 c pointers

代码是

char** p = (char **) malloc(sizeof(char **) * size); //Where size is some valid value.
p[1] = (char*) malloc(sizeof(char) * 30);
Run Code Online (Sandbox Code Playgroud)

以上代码是否正常?

我的理解是

p -> +---------+
     0 char*   + -> {c,o,d,e,\0}
     +---------+

     +---------+
     1 char*   + -> {t,o,a,d,\0} //The assignment of these values is not shown in the code.
     +---------+
Run Code Online (Sandbox Code Playgroud)

所以我们应该写

char** p = (char **) malloc(sizeof(char *) * size);
Run Code Online (Sandbox Code Playgroud)

我对么?

并且p [0]表示*(p + 1)其中p + 1将指向"toad",因此将返回"toad"?

Mit*_*eat 8

作为一般规则,你采用malloc调用内部大小的东西的'*-ness'应该比接收malloc内存的指针小1'*'.

例如:

char * p = malloc(sizeof(char) * somesize);
Run Code Online (Sandbox Code Playgroud)

char ** p = malloc(sizeof(char *) * somesize);
Run Code Online (Sandbox Code Playgroud)