4

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++ 初学者,根本不明白为什么会发生这种情况......我知道这种代码不应该......但是,任何人都可以解释那里发生了什么吗?

4

4 回答 4

6

这是未定义的行为。&foo[0]为您提供第一个std::string对象的地址,然后从中减去 4。从 §5.7 加法运算符:

如果指针操作数和结果都指向同一个数组对象的元素,或者超过数组对象的最后一个元素,则计算不应产生溢出;否则,行为未定义。

未定义的行为意味着您可以体验任何事情。可能发生的是某个内存区域,即数组开头之前的四个位置,即不是有效std::string对象被视为std::string. 这势必导致丑陋的事情发生。

于 2013-03-22T00:42:58.507 回答
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

于 2013-03-22T01:26:08.567 回答
1
  cout << *(&foo[0]-4) << endl;

此代码用于打印 foo[-4]

试试这个代码。

 cout << *(&foo[4]-4) << endl;

这将打印 foo[0]

 T * p;
 int n;

p+n表示padd 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]
于 2013-03-22T00:52:31.960 回答
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. 
于 2013-03-22T00:53:07.410 回答