为什么在下面的代码中 int *p = 22 会导致编译时错误,而 ptr 成功打印出值。
int main()
{
/*taking a character pointer and assigning a string to it*/
char *ptr = "Stackoverflow" ; //correct
/*taking a int pointer and assigning a string to it*/
int *p = 22 ; //incorrect
printf("%s",ptr); // correct and print
printf("%d",p); //incorrect and give compile time error.
return 0;
}
int
,理论上应该可以工作。如果该地址未被分配,则您的程序将崩溃。话虽如此,这不是您应该或应该做的事情。如果您尝试编译该行,您会注意到编译器警告“int*与int的间接级别不同”,其中22是int。出于很好的原因,发出了该警告!您只应使用calloc
或malloc
或使用&
运算符来分配指针。 - Nikchar *ptr = "Stackoverflow"
可以工作。 - Nik