All of the interesting technological, artistic or just plain fun subjects I'd investigate if I had an infinite number of lifetimes. In other words, a dumping ground...

Thursday, 21 August 2008

C++: pointers can't be changed in functions

Can update what the pointer points to but not the pointer.

#include <iostream>
    int t1;
    int t2;

void upPoint(int * s1)
{
    printf("upPoint: p1 before %p, %d\n", s1, *s1);
    s1 = &t2;
    printf("upPoint: p1 after  %p, %d\n", s1, *s1);
}

int main()
{
   t1 = 1;
   t2 = 2;
   int * p1 = &t1;

   printf("p1 before %p, %d\n", p1, *p1);
   upPoint(p1);
   printf("p1 after  %p, %d\n", p1, *p1);

}

g++ -Wall -o pointUpdate pointUpdate.cc

[tohare@masrtcsdev01 test]$ ./pointUpdate
p1 before 0x8049b60, 1
upPoint: p1 before 0x8049b60, 1
upPoint: p1 after  0x8049b64, 2
p1 after  0x8049b60, 1

No comments:

tim's shared items

Add to Google Reader or Homepage