Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

c++ - Adding an offset to a pointer

If I have a pointer to an object and I want to get a pointer to an object that is say 16 bytes after the pointer how do I add the 16 byte offset to the pointer?

Also, memory addresses in 32bit systems look like this 0x00000000. If I change an address like 0x00000001 to 0x00000002 how many bytes are skipped?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Pointers count bytes, so to point at the next byte you would need to change a pointer's value by 1. Pointer arithmetic, however, counts the objects pointed to by the pointer, and incrementing a pointer increases its value by the size of its pointee type. If you want to point at bytes, use a char pointer, since char has size 1 by definition, and pointer arithmetic on char pointers is lets you point at bytes:

T * p  = get_pointer();

char * cp = reinterpret_cast<char*>(p);

cp += 16;

Casting pointers to and from char types does not constitute type punning and is explicitly allowed by the standard. However, you must not use the resulting pointer to access any objects that aren't actually at that address.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...