char *charPtr = malloc(50);

char *charPtr; *charPtr = malloc(50);

像上面的示例一样,我一直在C中创建指针。可以确定这两个在C中相同吗?

最佳答案

可以确定这两个在C中相同吗?


不,您需要初始化指针。

char *charPtr = malloc(50);  // initialization


或者,您先声明它,然后再分配它:

char *charPtr;  // declaration
charPtr = malloc(50);  // <-- assignment - do NOT add * here as the you already declared `charPtr` as a pointer


请注意,像您那样做(第二种情况)是错误的:

char *charPtr;
*charPtr = malloc(50);  // <-- WRONG, the * here is deference operator

关于c - 指针声明对等,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35422256/

10-09 15:32