pointer arithmetic

Jan 17, 2015 at 5:34pm
1
2
3
4
5
6
7
8
int _tmain(int argc, _TCHAR* argv[]) {
	std::string words;
	std::string *ptr = &words;
std::cin >> *ptr;
--ptr;
std::cin >> *ptr;
keep_window_open();
}

first , in line 4 i cin the *ptr which will overwrite the value of words
then in line 5 i decremented the address ( 16 bytes ) ,which ptr holds , but line 6 doesnt seem to work , it crashes. i think it got something to do with memory
Last edited on Jan 17, 2015 at 5:34pm
Jan 17, 2015 at 5:39pm
What exactly are you trying to accomplish with this code?
Jan 17, 2015 at 5:48pm
this one
std::cin >> *ptr;
but it is crashing
Jan 17, 2015 at 5:49pm
You are writing in memory which does not belong to you.
Last edited on Jan 17, 2015 at 5:50pm
Jan 17, 2015 at 5:52pm
Again I ask, what is the goal of this code? If you describe the goal, perhaps we can help you by showing you the correct way to do it.
Jan 17, 2015 at 5:55pm
You are writing in memory which does not belong to you. 

so i should make a new variable for ptr to hold?
1
2
3
4
std::string words;
std::string *ptr = &words;
std::string word2;
--ptr = &word2;

like that?
Jan 17, 2015 at 6:08pm
what is the goal of this code?

im trying to make the user input on --ptr
Jan 17, 2015 at 6:09pm
So you are trying to read more than one string from a user by using pointers?
1
2
3
4
5
6
std::string words[2]; //allocate space for two strings
std::string* ptr = &words[0]; //store memory address of the first string to ptr

std::cin >> *ptr; //read a string and store it to the first spot in words array
ptr++; //increment the memory address, basically "move" ptr to the next spot
std::cin >> *ptr; //read a string and store it to the second spot in words array 
Jan 18, 2015 at 7:07am
so it is impossible to write into address without its own owner?
Jan 18, 2015 at 10:44am
Lets put it this way:
You are about to receive a packet with million dollars in it. The delivery company has been given your address, but told to leave the packet to "the next building". They don't actually know whether there is a building next to yours, or who there lives. Do you think that you are then able to use your money?

When you have no idea what a memory location contains, how could you possibly write (or read) anything sensible there?
Topic archived. No new replies allowed.