Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - Pointer addition and element size

At: http://www.fredosaurus.com/notes-cpp/arrayptr/26arraysaspointers.html

Under: Pointer addition and element size

There is the following code:

// Assume sizeof(int) is 4.
int b[100];  // b is an array of 100 ints.
int* p;      // p is a a pointer to an int.
p = b;       // Assigns address of first element of b. Ie, &b[0]
p = p + 1;   // Adds 4 to p (4 == 1 * sizeof(int)). Ie, &b[1]

How did "p" in the last line become "4"?

Thanks.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

(I assume that you mean "1" in the last line, not "p")

Pointer arithmetic in both C and C++ is a logical addition, not a numeric addition. Adding one to a pointer means "produce a pointer to the object that comes in memory right after this one," which means that the compiler automatically scales up whatever you're incrementing the pointer with by the size of the object being pointed at. This prevents you from having a pointer into the middle of an object, or a misaligned pointer, or both.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...