Slackware在这里。我只是搞乱内存和指针...我想学习更多关于那些,所以我在c ++中创建了一个数组,并查找了其中第一项的内存地址...:
string foo[3] = {"a", "b", "c"};
cout << *(&foo[0]-4) << endl;
输出了这个:http://pastebin.com/K0HAL5nJ 整个代码:
#include <iostream>
using namespace std;
int main()
{
string foo[3] = {"a", "b", "c"};
cout << &foo[0] << " minus " << &foo[1] << " equals " << int(&foo[0])-int(&foo[1]) << endl;
cout << *(&foo[0]-4) << endl;
cout << "Hello world!" << endl;
return 0;
}
我是c ++的完全初学者,并且不明白为什么会发生这种情况......我知道这种代码不应该......但是,仍然可以请任何人解释那里发生的事情吗?
答案 0 :(得分:6)
这是未定义的行为。 &foo[0]
为您提供第一个std::string
对象的地址,然后从中减去4。来自§5.7添加剂运算符:
如果指针操作数和结果都指向同一个数组对象的元素,或者指向数组对象的最后一个元素,则评估不应产生溢出;否则,行为未定义。
未定义的行为意味着您可以体验任何事物。可能发生的是一些内存区域,在数组开始之前的四个位置,即不是有效的std::string
对象被视为std::string
。这必将导致丑陋的事情发生。
答案 1 :(得分:2)
向指针添加整数时,整数乘以指针指向的类型的元素大小。
// 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]
http://www.fredosaurus.com/notes-cpp/arrayptr/26arraysaspointers.html
答案 2 :(得分:1)
cout << *(&foo[0]-4) << endl;
此代码用于打印foo [-4]
试试这段代码。
cout << *(&foo[4]-4) << endl;
这将打印foo [0]
T * p;
int n;
p+n
表示地址p
添加sizeof(T *)* n
指针添加和元素大小
向指针添加整数时,整数乘以指针指向的类型的元素大小。
// 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]
答案 3 :(得分:1)
您正在访问一些超出您分配的数组的地址空间的内存,这会导致未定义的行为。
string foo[3] = {"a", "b", "c"};
cout << &foo[0] << " minus " << &foo[1] << " equals "
<< int(&foo[0])-int(&foo[1]);
&foo[0] get the memory address of "a",
&foo[1] get the memory address of "b";
the output is OK since both address are in range of foo's address space
cout << *(&foo[0]-4) << endl;
You tried to get the value at address of ("a" -4),
since this address is outside the address of foo, it is undefined behavior.