即使在 malloc 声明中将其类型转换为整数类型之后,每当我取消引用指针时,如果不显式地对其进行类型转换,则无法使用 ptr。任何人都可以解释为什么在我对其进行类型转换后,指针不会永远转换为 int* 。
void *ptr;
ptr = (int*)malloc(sizeof(int));
*ptr = 1; // This line does not work even after typecasting in the above line
*(int*)ptr = 1; //This line works
最佳答案
问题出在第一行中的 ptr
声明。你似乎希望它是
int *ptr; /* NOT void* */
否则你每次都必须施放它。 C/C++ 使用编译时声明,并且对 malloc
的强制转换在它出现的行之后不起作用。特别是
ptr = (int*)malloc(sizeof(int)); /* the (int*) HAS NO EFFECT when ptr is declared void* */
关于c - 即使在类型转换之后,是否每次都需要取消引用 void 指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51332492/