Monday, 20 September 2010

C(++) and Pointers

Been playing with C and C++ variable declarations and pointers (using Microsoft Visual Studio 2010) last few mornings. This code should serve as good reference in future:
#include <iostream>

using namespace std;

int intFunc(int x, int *p, int **pp) {
return x;
}

int *pointerFunc(int x, int *p, int **pp) {
return p;
}

int **pointerPointerFunc(int x, int *p, int **pp) {
return pp;
}

int main()
{
int x, *p, **pp;
int resultx, *resultp, **resultpp;

x=5;
p = &x;
pp = &p;

cout<<"HEY, you, I'm alive! Oh, and Hello World!\n";
printf( "x = %d\n", x );
printf( "&x = %d\n", &x );
printf( "p = %d\n", p );
printf( "*p = %d\n", *p );
printf( "&p = %d\n", &p );
printf( "pp = %d\n", pp );
printf( "*pp = %d\n", *pp );
printf( "**pp = %d\n", **pp );
printf( "&pp = %d\n", &pp );

resultx = intFunc(x,p,&p);
printf( "resultx (intFunc) = %d\n", resultx );

resultp = pointerFunc(x,p,&p);
printf( "resultp (pointerFunc) = %d\n", resultp );

resultx = *pointerFunc(x,p,&p);
printf( "resultx (*pointerFunc) = %d\n", resultx );

resultpp = pointerPointerFunc(x,p,&p);
printf( "resultr (pointerPointerFunc) = %d\n", resultpp );

resultp = *pointerPointerFunc(x,p,&p);
printf( "resultp (*pointerPointerFunc) = %d\n", resultp );

resultx = **pointerPointerFunc(x,p,&p);
printf( "resultx (**pointerPointerFunc) = %d\n", resultx );

cin.get();
}

No comments: