简体   繁体   English

元素及其以外的指针算术。 此代码有什么问题?

[英]pointer arithmetic on elements and beyond. what is wrong with this code?

Please, what is wrong with this code. 请,这段代码有什么问题。 it's supposed to print until y[4] and then break out of the while loop, but it prints until y[12] and breaks thence; 它应该打印到y [4],然后退出while循环,但是它打印到y [12],然后中断; I think printing between y[5] to y[12] is wrong. 我认为在y [5]到y [12]之间打印是错误的。 It was taken from a website as an example that pointer arithmetic is limited to the elements of the array and one element beyond. 以一个网站为例,指针算术仅限于数组的元素和超出范围的一个元素。

#include <stdio.h>

int main()
{
   int i = 0;
   int x[5] = {0, 1, 2, 3, 4};
   int y[5];
   int *ptr = x;
   while (&y[i] != (ptr+5)){
        y[i] = x[i];
        printf("Value of y[%d] is : %d\n", i, y[i]);
        i++;
   }

   return 0 ;
}

您的条件(&y[i] != (ptr+5)是错误的。Y是指向内存中与x完全不同的区域的数组。因此条件将保持为真。

The condition &y[i] != (ptr+5) does not make sense here. 条件&y[i] != (ptr+5)在这里没有意义。 Why are you comparing y with ptr ? 为什么将yptr进行比较? They are pointing to different memory locations. 他们指向不同的内存位置。 They can never be the same since they are pointing at two different locations. 因为它们指向两个不同的位置,所以它们永远不能相同。 You just need to check for this: 您只需要检查以下内容:

while (i<5)

See full code here . 在此处查看完整代码。

There is no guarantee that the array y will be placed at a specific position in relation to the array x . 不能保证将数组y放置在相对于数组x的特定位置。 So what you are exploiting is compiler-specific behavior, that may change depending on compiler used, compiler version or even compiler flags. 因此,您要利用的是特定于编译器的行为,该行为可能会因所使用的编译器,编译器版本甚至编译器标志而异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM