简体   繁体   English

指针未递增(移动)到预期位置或指针算法未提供预期答案

[英]Pointer is not incremented (moved) to expected location or pointer arithmetic is not providing expected answer

In the following snippet of code I expect pointer to move to next location ie current location + sizeof(datatype) but not happening unless I type cast to int .在下面的代码片段中,我希望指针移动到下一个位置,即当前位置 + sizeof(datatype)但除非我键入 cast to int否则不会发生。

#include <iostream>
#include <string.h>

int sizeOf()
{
    int a = 0;
    int* b = &a;
    int* c = &a;
    c++;// expect pointer to move "current location + sizeof(int)"
    return c - b;
}


int main()
{
    std::cout << "Size of int is " << sizeOf() << ", actual size of int is  "<< sizeof(int) << "\n";
    return 0;
}

Output: Output:

Size of int is 1, actual size of int is  4

Expectation: if I increment pointer of type int then pointer should move to current location + sizeof(int) but not happening期望:如果我增加int类型的指针,那么指针应该移动到当前位置 + sizeof(int)但不会发生

But it actually works when I use following line但是当我使用以下行时它实际上有效

return (int)c - (int)b;

Compiler warns编译器警告

my-pc $ g++ test.cpp -fpermissive
test.cpp: In function ‘int sizeOf()’:
test.cpp:10:17: warning: cast from ‘int*’ to ‘int’ loses precision [-fpermissive]
   10 |     return (int)c - (int)b;
      |                 ^
test.cpp:10:26: warning: cast from ‘int*’ to ‘int’ loses precision [-fpermissive]
   10 |     return (int)c - (int)b;
      |                          ^

my-pc $ ./a.out 
Size of int is 4, actual size of int is  4

Now I got the output what I expect.现在我得到了我所期望的 output。 I know int* is typecasted to int .我知道int*被强制转换为int I want to know the reason why it did not worked in first case and worked later.我想知道它在第一种情况下不起作用并在以后起作用的原因。

The difference is in terms of the size of the pointed object.区别在于尖头 object 的大小。

So a difference of 1 means the pointers point to 1 * sizeof(int) bytes apart.所以1的差异意味着指针指向1 * sizeof(int)字节。

For example,例如,

&( a[2] ) - &( a[0] )

always gives 2 for a C array.对于 C 数组,总是给出2 It doesn't matter if it's an array of char , int , or some struct .它是charint还是某个struct的数组都没有关系。

And it's easy to show why this is necessary, given that a[i] is equivalent to *(a+i) for a C array.并且很容易说明为什么这是必要的,因为对于 C 数组, a[i]等效于*(a+i)

   &( a[2] ) - &( a[0] )
=  &( *( a + 2 ) ) - &( *( a + 0 ) ) 
=  ( a + 2 ) - ( a + 0 )
=  2

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

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