changing values in Pointer to pointer and pointer to address

I have these to following codes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  #include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    char sting[10];
    strcpy(sting,"this value wont change");

    char * ptr = sting;
 strcpy(sting,"it is now changed!");
    cout<<ptr<<endl;
  
  
    system("PAUSE");
    return EXIT_SUCCESS;
}


Result: "It is now changed!"



the other one is


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
   char * sting = "this value wont change!";

    
    char * ptr = sting;
    sting="it is now changed!";
    cout<<ptr<<endl;
  
  
    system("PAUSE");
    return EXIT_SUCCESS;
}


Result: this value wont change!



I'm confused, how come it didnt change when i tried printing it using the pointer?
Why?

In your second bit of code:

1. you define a char* variable sting which points at value 1

2. you define a new char* valiable ptr, initializing it to point at the same place as sting. i.e. value 1

3. you set the old variable sting to point at a new value (value 2)

4. you output the new char* valiable ptr which is still pointing at the old value (value 1), as that's what you set it to in step 2.

So you get the old value (value 1)

Andy

PS In your first bit of code you set ptr to point at your buffer sting and then copy the new value into the buffer.
Last edited on
Topic archived. No new replies allowed.