Tuesday 22 April 2014

[C++] Pointers

Noted down the important concepts:
1. Reference Operator (&)
ex.
myvar = 25;  
foo = &myvar;
bar = myvar; 

2. Dereference Operator (*)
ex.
baz = *foo;

3. Pointers & Arrays
It collects so many ways to get address from an array and set value to an array.
#include <iostream>
using namespace std;

int main ()
{
  int numbers[5];
  int * p;

  p = numbers;
  *p = 10;

  p++;
  *p = 20;

  p = &numbers[2];
  *p = 30;

  p = numbers + 3;
  *p = 40;

  p = numbers;
  *(p+4) = 50;

  for (int n=0; n<5; n++)
    cout << numbers[n] << ", ";
  return 0;
Output:
10, 20, 30, 40, 50,

4. Pointers and Const
int x;
      int *       p1 = &x;  // non-const pointer to non-const int
const int *       p2 = &x;  // non-const pointer to const int
int const *       p3 = &x;  // also non-const pointer to const int
      int * const p4 = &x;  // const pointer to non-const int
const int * const p5 = &x;  // const pointer to const int 

5. Pointers to Pointers
char a;
char * b;
char ** c;

a = 'z';
b = &a;
c = &b;

6. Pointers and 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;
}
Output:
8
Mostly, we use function point in sqort().

7. Arrow
Same description below:
(*p).foo;
p->foo;

Ref. http://www.cplusplus.com/doc/tutorial/pointers/

No comments:

Post a Comment