本文介绍了C ++ - 指针添加和元素大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在:
下:指针添加和元素大小
有以下代码:
// 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 ?
感谢。
推荐答案
1在最后一行,而不是p)
(I assume that you mean "1" in the last line, not "p")
C和C ++中的指针算术是一个逻辑 >数字添加。将一个添加到指针意味着产生一个指向该内存中的对象的指针,这意味着编译器自动扩展任何你正在增加的指针与被指向的对象的大小。这可以防止您有指向对象中间或指针未对齐的指针,或两者都有。
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.
这篇关于C ++ - 指针添加和元素大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!