Showing posts with label pointer. Show all posts
Showing posts with label pointer. Show all posts

Thursday, November 3, 2011

The Reference-to-Pointer Syntax in C++

The syntax of pointer declarations is sometimes difficult to decipher, just consider the following three, elementary cases:
  • int *p[2]
  • int (*p)[2]
  • int (*p)()

 

Example 1

int *p[2];
This is actually an array of two int pointers. We can also think of this as a pointer to two consecutive int pointers.

int *p[2];

int *a = new int;
*a = 21;
int *b = new int;
*b = 22;

p[0] = a;
p[1] = b;

std::cout << *p[0] << std::endl;          // 21
std::cout << *p[1] << std::endl;          // 22

int **q = p;

std::cout << **q << std::endl;
std::cout << **(q + 1) << std::endl;

delete a;
delete b;
http://codepad.org/6c07RgKf

 

Example 2

int (*p)[2];
This is a pointer to an array of two ints. Just as in the first example, we can think of this a pointer to a pointer, since an array is basically a const pointer.


int n[2];
n[0] = 4;
n[1] = 7;

int (*p)[2] = &n;

std::cout << (*p)[0] << std::endl;       // 4
std::cout << (*p)[1] << std::endl;       // 7

// or ...

std::cout << **p << std::endl;           // 4
std::cout << *(*p + 1) << std::endl;     // 7
http://codepad.org/UDcH5cIQ

 

Example 3

int (*p)();
This is a pointer to a function returning an int.
int takeThisInt()
{
    return 123;
}

// ...

int (*p)() = &takeThisInt;
int x = p();                      // note the parentheses
std::cout << x << std::endl;      // 123
http://codepad.org/iL701mg5