问题描述
在: http://www.fredosaurus.com/notes-cpp/arrayptr/26arraysaspointers.html
下:指针的添加和元素大小
有以下代码:
// 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]
最后一行中的"p"如何变成"4"?
How did "p" in the last line become "4"?
谢谢.
推荐答案
(我假设您在最后一行中表示的是"1",而不是"p")
(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.
这篇关于指针添加和元素大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!