Tuesday, November 19, 2013

pointer in c

Pointer in c is not simple to understand, but it's not that difficult either.
So for instance, "int* ip;",  it's not a big deal.
But how about "int** ip";   or  "int*** ip;" ? In no time, it will make you dazed and confused, sometimes it happens to even an experienced c programmer.

What I try to do here is to explain it in a new way that hopefully can prevent you from feeling dazed when you deal with them.

1. First, let me borrow template parameter concept in C++ here to use "T" to represent a type, which could be any type like int, int*, int**, float, etc.  Yep, consider "int*" and "int**" as type as well.

2. Next, make an alias of "T*" , you see "T*" as a whole as a new type, which holds memory location, similar to int, which holds integer.

typedef T* addr; 

For example, 

addr  =   int*   if  T = int
addr = int**   if T = int*
addr = double  if T = int**



typedef int* addr;
int a;     // a holds an integer
addr  b; // b holds a memory address (containing int)


==================================
Here is a piece of code for demo:
==================================

typedef int* addr;
 
// two memory addresses passed in by value.
void f(int* ip, addr* ia)        // equal to    void f(int* ip, int** ia)
{
   // By the way, once you get addresses passed in, the only thing you can do inside a function
   // is to manipulate the contents in them via *ip, for instance.

    // Modify the content in the first memory location passed in.
    // so new integer value 4 is stored in that location. 
    int a = 1000;    // int type
    *ip = a;

        addr  b = (int*)malloc(3 * sizeof(int));   // addr type
        b[0] = 11;
        b[1] = 12;
        b[2] = 13;

    // Modify the content in the second memory location passed in.
    // !!! so new addr value b ( address) is stored in that location. !!!
    // This is AMAZING !!! Reason is that we are sending out a memory location out back to 
    // calling function. For example, you allocate a chunk of dynamically allocated memory within
    // the function, calling function will have access to the chunk of memory. 
    *ia = b;
}

int main(void) {
    int a=3;
    addr  ia;

    // I want you to think "addr" as any ordinary type such as "int". Forget about pointers!!!!
    // I send their addresses into a function and update their contents inside the function f().  
    f(&a, &ia);

   cout << a << endl;

    cout << ia[0] << endl;
    cout << ia[1] << endl;
    cout << ia[2] << endl;

    return 0;
}

No comments:

Post a Comment