Slackware here. I was just messing around with memory stuff and pointers... I wanted to learn a bit more about those, so I made an array in c++, and looked up the memory address of the first item in it...:
string foo[3] = {"a", "b", "c"};
cout << *(&foo[0]-4) << endl;
It outputted this: http://pastebin.com/K0HAL5nJ The whole code:
#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;
}
I am a complete beginner in c++ and do not understand why this happens at all... I know that this sort of code is not supposed to... be, but still, could anyone please explain what happened there?
It's undefined behaviour. &foo[0]
gives you the address of the first std::string
object, which you then subtract 4 from. From §5.7 Additive operators:
If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.
Undefined behaviour means you could experience anything. What is probably happening is some area of memory, four positions before the beginning of the array, that is not a valid std::string
object is being treated as a std::string
. This is bound to lead to ugly things happening.
When you add an integer to a pointer, the integer is multiplied by the element size of the type that the pointer points to.
// 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With