Monday, June 15, 2015

Pointers 101 [Refresher C++]

The address of a variable can be obtained by preceding the varable name with ampersand (&).

x = 25;
foo = &x;
bar = x;

Let the address of x = 123;
then the value of foo = 123  and bar = 25.

We can dereference a variable using Asterisk (*)

bas = *foo; 

This can be said "bas equal to value pointed by foo."

The reference and dereference operators are complementary.

bas = foo;   // bas equal to foo (123)
bas = *foo;  // bas equal to value pointed to by foo (25)

Here is a quick script I wrote that gives a quick demonstration of pointers, how they relate with one another and the double pointers concept.
#include <stdlib.h>

int main() {
        int* foo;
        int* (*bar);
        int val = 25;

        foo = &val;
        bar = &foo;
        printf("Adr of val: %p\n", &val);
        printf("Val of val: %p\n", val);

        printf("Adr of foo: %p\n", &foo);
        printf("Val of foo: %p\n", foo);
        printf("Drf of foo: %p\n", *foo);

        printf("Adr of *bar: %p\n", &bar);
        printf("Val of *bar: %p\n", bar);
        printf("Drf of *bar: %p\n", *bar);
        return 0;
}
Output:
Adr of val: 0x7fff735c829c
Val of val: 0x19
Adr of foo: 0x7fff735c82a8
Val of foo: 0x7fff735c829c
Drf of foo: 0x19
Adr of *bar: 0x7fff735c82a0
Val of *bar: 0x7fff735c82a8
Drf of *bar: 0x7fff735c829c

Pointers to functions C++ allows operations with pointers to functions. The use of this is for passing a function as an argument to another function.
Pointers to functions are declared with the same syntax as a regular function declaration, except that the name of the function is enclosed between parentheses () and an asterisk (*) is inserted before the name:

// pointer to functions
#include <iostream>
using namespace std;

int addition (int a, int b)
{ return (a+b); }

int subtraction (int a, int b)
{ return (a-b); }

int operation (int x, int y, int (*functocall)(int,int))
{
  int g;
  g = (*functocall)(x,y);
  return (g);
}

int main ()
{
  int m,n;
  int (*minus)(int,int) = subtraction;

  m = operation (7, 5, addition);
  n = operation (20, m, minus);
  cout <<n;
  return 0;
}

In the example above, minus is a pointer to a function that has two parameters of type int. It is directly initialized to point to the function subtraction.

Yet Another Example


typedef int (*t_somefunc)(int,int);
int product(int u, int v) {
  return u*v;
}

t_somefunc afunc = &product;
...
int x2 = (*afunc)(123, 456); // call product() to calculate 123*456

Sources:
http://www.cplusplus.com/
http://www.stackoverflow.com/