简体   繁体   中英

Convert int to int pointers address

c++

p is pointing to specific place

int * p

When I try p=p[1] it says can't convert int to int (using devcpp).

While p=&p[1] works fine

Why do I need to do the second method? p[1] is an address. So the first method should work? Can you explain me about this error?

p[1] is the same as *(p + 1) .

You want the address of this element, which is simply (p + 1) . C++ also allows &p[1] , as you noticed.

p[1] is equivalent to *(p + 1) so it's a value, not an address. p = p + 1 or just p++ would be what you want.

While p is an int* , p[1] is an element from that array, therefore p[1] is int .

You can do p = &p[1] in other ways, for instance, p = p + 1 , or p++ . Both will set p to the same final value.

Notice when doing such arithmetic operations with pointers, it will not not increment the address by 1, its incrementing it by 1 times the size of one element, so its really the same thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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