Question

I am trying to pass a single pointer and double pointer in a function. but its giving me error.

int main()
{
    int *pt;

    fun(pt);
    .
    .
}

fun(int *pt)
{
    pt=(int*)malloc(6*sizeof(int));
    .
    .
}

and what is the syntax when we are using double pointer. Can anybody just describe it with an example or can edit the above example. I shall be very thankful to you.

Was it helpful?

Solution

The fundamental idea of reference semantics is that a function modifies some other object that exists outside the function's own scope. You can implement reference semantics in C by passing the address of the object that is being referenced to a function that takes an argument of type "pointer to the type of the object".

The crucial hallmark of "reference semantics via pointers" consists of these two points:

  • The caller takes the address of something (via the &-operator).
  • The callee dereferences the argument.

For example:

Caller:

T x;
f(&x);         // address-of

Callee:

void f(T * p)  // take argument as pointer
{
    (*p).y = 20;  // dereference (via *)
    p->x = 10;    // dereference (via ->)
}

In your situation, T = int *:

int * pt;
fun(&pt);              // function call takes address

void fun(int ** p)     // function takes pointer-to-object...
{
    *p = malloc(173);  // ...and dereferences to access pointee
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top