#include <stdio.h>
int func(int *p , int n)
{
for(int i = 0 ; i < n ; i ++)
{
printf("%d\n", *(p + i));
*(p + i) +=1;
p = ++p;
printf("%d\n", p);
}
}
int main()
{
int arr[5] = {1,2,3,4,5};
func(arr, 5);
for(int i = 0 ; i < 5 ; i ++)
{
printf("%d\t %d\n", arr[i], &arr[i]);
}
}
控制台上的输出。
1
-2128162268
3
-2128162264
5
-2128162260
0
-2128162256
4195824
-2128162252
2 -2128162272
2 -2128162268
4 -2128162264
4 -2128162260
6 -2128162256
为什么... *(p + i) +=1;
这里存储在p中的地址每次都会改变。
例子 - 如果我们有一个4个整数的数组----。
p = &a[0];
&a[0] = 200
then, p + 1 = 200 + 4
p + 2 = 200 + 8
在上面的程序中,p中存储的地址一旦被递增,就不是数组的基地址。
谁能解释一下?到底是哪里出了问题?
编辑 : 解决了,供以后参考。程序是这样的
i = 0
*(p + 0) = *(-2128162272 + 0) = *(-2128162272) = Value to be incremented at &a[0]
p ++
p = -2128162268
i = 1
*(p + 1) = *(-2128162268 + 4) = *(-2128162264) = Value to be incremented at &a[3]
p = -2128162264
i = 2
*(p + 2) = *(-2128162264 + 4 * 2) = *(-2128162256) = Value to be incremented at &a[5]
p = -2128162260
i = 3
*(p + 3) = *(-2128162260 + 4 * 3) = *(-2128162252) = Value to be incremented at address -2128162252
p = -2128162256
为什么*(p + i) +=1; 没有像预期的那样递增?
因为你是在引用 p + 1
你正在递增p指向的数组中下一个地址的内容。
代码中还有一些其他问题,我修改了一些并添加了注释。
#include <stdio.h>
int func(int *p , int n) //return needed
{
for(int i = 0 ; i < n ; i++)
{
printf("%d\n", *(p + i)); //prints the value pointed by p[i]
*(p + i) +=1; //increments the value stored in p[i]
++p; //increments p, p = ++p; has no sequence point, it's undefined behavior
printf("%p\n", p); //printing the address %p specifier, prints the address p is currently pointing to
//needs to return an int
}
}
int main()
{
int arr[5] = {1,2,3,4,5};
func(arr, 5);
for(int i = 0 ; i < 5 ; i ++)
{
printf("%d\t %p\n", arr[i], &arr[i]); //same here, %p specifier for &arr[i]
}
}
输出
1
0x7ffffb6e6d54
3 //correct, incrementing pointer and i makes printf in the loop print every other value
0x7ffffb6e6d58
5
0x7ffffb6e6d5c
0 //since there are 5 loops, the last 2 will print out of bounds values
0x7ffffb6e6d60
4195824 //since there are 5 loops, the last 2 will print out of bounds values
0x7ffffb6e6d64
2 0x7ffe471c91a0 //value was incremented *(p + 1) += 1
2 0x7ffe471c91a4
4 0x7ffe471c91a8 //value was incremented *(p + 1) += 1
4 0x7ffe471c91ac
6 0x7ffe471c91b0 // value was incremented *(p + 1) += 1