views:

122

answers:

3

I am new to C and I was reading about how pointers "point" to the address of another variable. So I have tried indirect invocation and direct invocation and received the same results (as any C/C++ developer could have predicted). This is what I did:

int cost;
int *cost_ptr;

int main()
{
    cost_ptr = &cost;                          //assign pointer to cost
    cost = 100;                                //intialize cost with a value
    printf("\nDirect Access: %d", cost);
    cost = 0;                                  //reset the value
    *cost_ptr = 100;
    printf("\nIndirect Access: %d", *cost_ptr);
    //some code here

    return 0;                                  //1
}

So I am wondering if indirect invocation with pointers has any advantages over direct invocation or vice-versa? Some advantages/disadvantages could include speed, amount of memory consumed performing the operation (most likely the same but I just wanted to put that out there), safeness (like dangling pointers) , good programming practice, etc.
1Funny thing, I am using the GNU C Compiler (gcc) and it still compiles without the return statement and everything is as expected. Maybe because the C++ compiler will automatically insert the return statement if you forget.

A: 

In the "printf(..., *cost) case, the value of "cost" is copied to the stack. While trivial in this instance, imagine if you were calling a different function and "cost_ptr" pointed to a multi-megabyte data structure.

Steve Emmerson
There is no "stack" in C, refer to such terms by their equivalent storage duration, i.e automatic in this case.
Mustapha Isyaku-Rabiu
+1  A: 

The pointer notation involves two memory fetches (or one fetch and one write) where the direct invocation involves one.

Since memory accesses are slow (compared to computation in registers; fast compared to access on disk), the pointer access will slow things down.

However, there are times when only a pointer allows you to do what you need. Don't get hung up on the difference and do use pointers when you need them. But avoid pointers when they are not necessary.

Jonathan Leffler
+4  A: 

Indirect and direct invocation are used in different places. In your sample the direct invocation is prefered. Some reasons to use pointers:

  • When passing a large data structure to a function one can passa pointer instead of copying the whole data structure.
  • When you want a function to be able to modify a variable in the calling function you have to pass a pointer to the original variable. If you pass it by value the called function will just modify a copy.
  • When you don't know exactly which value you want to pass at compile time, you can set a pointer to the right value during runtime.
  • When dynamically allocating a block of memory you have to use pointers, since the storage location is not known until runtime.
Anders Abel