【发布时间】:2020-05-07 08:09:00
【问题描述】:
我最近切换到 C 并试图找出指针。
#include <stdio.h>
int main()
{
int arr[5] = {1,2,3,4,5};
int *a = &arr;
printf("Array : %p\n", arr);
for(int i=0; i<5; i++)
{
printf("Value and Address of Element - %d : %d\t%p,\n", i+1, arr[i], &arr[i]);
}
printf("Pointer to the Array : %p\n", a);
printf("Value pointed by the pointer : %d\n", *a);
a = (&a+1);
printf("Pointer after incrementing : %p\n", a);
return 0;
}
但是,以下行似乎不起作用。
a = (&a+1);
打印指针a的递增值后,它仍然指向数组(arr)。 这是程序的输出:
Array : 0x7ffe74e5d390
Value and Address of Element - 1 : 1 0x7ffe74e5d390,
Value and Address of Element - 2 : 2 0x7ffe74e5d394,
Value and Address of Element - 3 : 3 0x7ffe74e5d398,
Value and Address of Element - 4 : 4 0x7ffe74e5d39c,
Value and Address of Element - 5 : 5 0x7ffe74e5d3a0,
Pointer to the Array : 0x7ffe74e5d390
Value pointed by the pointer : 1
Pointer after incrementing : 0x7ffe74e5d390
如您所见,指针“a”仍指向第一个元素。但是,理论上不应“a”指向最后一个元素之后的任何内容(鉴于 &a + 1 将指针增加整个数组的大小 - 来源:difference between a+1 and &a+1)
有人能解释一下原因吗?
【问题讨论】:
-
int *a = &arr;不应编译。 -
C 和 C++ 是不同的语言,没有一种语言叫做“C/C++”。
-
确保启用所有警告,并将警告视为错误,特别是如果您是这些语言的初学者。即便如此,C 和 C++ 都有很多方法可以编写仍然未被编译器拒绝的无效程序。
-
@molbdnilo 不确定,但我可以想象它在 C 中很好。
-
在godbolt.org 上尝试使用多个编译器编写代码可能会有所帮助 - 通常错误消息会有所不同,并且某些编译器会比其他编译器更清楚地传达问题。
标签: c++ c arrays pointers pointer-arithmetic