请解释下面提到的程序的输出。我认为输出应该是 1 但它不是 1
#include <stdio.h>
int main()
{
int a[] = {1, 2, 3, 4, 5, 6};
int *ptr = (int*)(&a+1);
printf("%d ", *(ptr-1));
getchar();
return 0;
}
最佳答案
这是因为 &a
的类型是 int(*)[6]
因此 &a + 1 != &a[0] + 1
是你的意思,给定你的预期输出。
如果打印地址 &a
和 &a[0]
,它们将相同,但是递增 &a
与递增 &a[0]
因为 sizeof(int) != sizeof(int *)
,虽然这并不总是正确的,但您的代码不应该假设它是,或者依赖于它.
此外,您似乎正在使用强制转换,因为您的编译器提示 &a
是不兼容的指针类型,如果指针是兼容的类型,则不需要强制转换所以
#include <stdio.h>
int main()
{
int a[] = {1, 2, 3, 4, 5, 6};
int *ptr = &a[0] + 1;
printf("%d\n", *(ptr-1));
return 0;
}
应该只编译 find,输出将是 1
,如您所料。
关于c - c程序的程序输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29659099/