我有一个声明为的指针数组
char (*c)[20]
Run Code Online (Sandbox Code Playgroud)
使用malloc分配内存时
c=malloc(sizeof(char)*20);
Run Code Online (Sandbox Code Playgroud)
要么
c=(char*)malloc(sizeof(char)*20);
Run Code Online (Sandbox Code Playgroud)
我收到一条警告"可疑指针转换"
为什么?
在这个宣言中
char (*c)[20];
c对象有类型char (*)[20].
我们知道在C malloc返回类型中,void *并且在void *任何对象指针类型之间存在隐式转换.
因此c = malloc(whatever_integer_expression)在C中是有效的.如果收到警告,您可能正在使用C++编译器,或者您正在使用C编译器但忘记包含stdlib.h标准头.
但是c = (char*) malloc(whatever_integer_expression)无效的C是因为char *类型和char (*)[20]类型之间没有隐式转换.编译器必须(至少)发出警告.