Saturday, 1 March 2014

Pointer in c/c++

Definition
In this article, I will introduce my knowledge about pointer and how to use it.

In wiki:
In computer science, a pointer is a programming language object whose value refers directly to (or "points to") another value stored elsewhere in the computer memory using its address.
I think it is easy enough to know.


Syntax in c/c++
Overview about pointer

The basic syntax of declaring pointer in c/c++ are:
int *p;
char * q;
float * h;
...
Assign the memory for the pointer:
int a=20;
int *p=&a;

Here is my demo application written by c++ in codeblock
Pointer in c c++ tientuts
The left area is my code, right area is watches window show values when running this code and behind area is cmd window output some data.
And this is my code:


#include <iostream>

using namespace std;

int main()
{
    int i= 5;
    int* p_i= &i;

    int a[10];
    int *p_a =a;
    cout <<a<<" "<<&a<<" "<<p_a<<endl;
    int matrix[10][10];
    int * p_matrix = (int *)matrix;
    cout <<matrix<<" "<<&matrix<<endl;
    cout << "Hello world!" << endl;
    int** pp_i = &p_i;
    int*** ppp_i = &pp_i;
    return 0;
}



Normal variable

With i value, you can see in watches window: i is value of i and &i is address in memory (RAM) of i. Because i is not pointer so you can't use *i.

With p_i (pointer value): like i variable &p_i is address of p_i, p_i is value of p_i but p_i is the type of pointer contains the address of i so you can see p_i and &i is 0x28fef0. And to see and use value of address contain in p_i, we use *p_i. With *p_i you can access to get or set data of i. When *p_i change i will change too because they are only one address memory.
In c, command use &i:    scanf ("%d", &i);    because when function scanf get data from keyboard, it can change i value by use pointer like above.

Array
Array value is like pointer, you can see in output window of a &a and p_a.
But it has some advances like can use sizeof (view sizeof(matrix)).
To get values of array in pointer, use like this example:


for(int i=0;i<n;i++){
    printf("%d",*(f+i));
}
with n is length of array.

With matrix (two-dimensional array), you can use:


#include <iostream>

using namespace std;

int main()
{
    int matrix[2][3]={{1,2,3},{4,5,6}};
    int* p_matrix = (int *)matrix;
    for(int i=0;i<2;i++)
    {
        for(int j=0;j<3;j++)
            cout<<*(p_matrix+i*3+j);
        cout<<endl;
    }
    return 0;
}

pp_i and ppp_i are multi-level pointers.