Wednesday, November 20, 2013

T* : address type

I'm not sure term "address type" has been used in c yet, but I rather call pointer this way. Like "integer type"/int, whose value is integer, "address type"'s value is address, in which you can store everything: int, float, address, etc. Yep, you can store an address in another address. And if you like, you can do so recursively. As a result of that, you are dealing with T*, T**, T***, ...

When you see a struct like this, what do you see?
I'm sure it will make you dizzy if you're c programming beginner.

struct Node
{
   int data;
   Node* prev;
   Node* next;
};

But what I see is a node with three elements in there: one int and two addresses. It's no big different from a node with three ints in there.
struct Node
{
   int data;
   ADDR prev;
   ADDR next;
};


// 1. "T*" is called "address type": its value is an address, in which
// any ordinary type or "address type" can stay.
typedef int* ADDR;
typedef ADDR* ADDR2;
//typedef int** ADDR2;

// 2. Parameter pass to function in c is by value only.
// f() takes in int, ADDR and ADDR2 by value (copy of values).
// it has nothing to do with "int argument".
// but it DOES have something to do with "ADDR argument" 
// or "ADDR2 arguemnt" because it can play with the content
// in that address, which, in turn, causes post-effects after f() is gone.
void f(int a, ADDR b, ADDR2 c)
{
    a = 3;
    // change the content, which is int, in b
    *b = 20;
    // change the content, which is address, in c
    *c = b;
}


int main()
{
    int a;
    ADDR b = new int ;
    ADDR2 c = new ADDR;
    cout << "a is " << a << endl;
    cout << "b is  " << b <<  " what in b is " << *b << endl;
    cout << "c is  " << c <<  " what in c is " << *c << endl;
    f(a, b, c);
    cout << "a is " << a << endl;
    cout << "b is  " << b <<  " what in b is " << *b << endl;
    cout << "c is  " << c <<  " what in c is " << *c << endl;

    return 0;
}


Result:
1. None of a, b, or c's value after f() has changed, that's what     
    pass-by-value  means.
2. What is changed is the contents in these addresses: b and c.
    b's content (int) changed from 0 to 20.
    c's content (ADDR) changed from 0 to 0xbd46010

a is 0
b is  0xbd46010 what in b is 0
c is  0xbd46030 what in c is 0
a is 0
b is  0xbd46010 what in b is 20     
c is  0xbd46030 what in c is 0xbd46010

No comments:

Post a Comment