pointer arithmetic

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
What exactly are you trying to accomplish with this code?
this one
std::cin >> *ptr;
but it is crashing
You are writing in memory which does not belong to you.
Last edited on
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.
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?
what is the goal of this code?

im trying to make the user input on --ptr
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 
so it is impossible to write into address without its own owner?
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.