0
#include<stdio.h>
int main(){
    int *j;
    void fun(int**);
    fun(&j);
    return 0;
}

void fun(int **k){
    int a=10;
    /* Add a statement here */
}

In the following program add a statement in the function fun() such that address of a gets stored in j? Can someone please explain this whole program. I am not able to get this meaning of **.

André Teixeira
  • 2,392
  • 4
  • 28
  • 41
Surbhi Jain
  • 369
  • 1
  • 11
  • 1
    This might help: http://stackoverflow.com/questions/5727/what-are-the-barriers-to-understanding-pointers-and-what-can-be-done-to-overcome – R Sahu Oct 04 '14 at 05:01

1 Answers1

0

All you want is: *k = &a;

The ** thing means it is a pointer to a pointer. I think the following diagram will make it clear. Open the image in a new tab to see it clearly. enter image description here Read more here.

Shravan
  • 2,809
  • 2
  • 18
  • 39
  • but doesnt it mean **k=&j so, *(*k)=&j, so f j=0,&j=1 and **k=1 – Surbhi Jain Oct 04 '14 at 05:12
  • @user3867445: not really. `int **k` means that `**k` is an `int`, and `*k` is an `int *` or `int` pointer. Since we also have `int a`, we can deduce that `&a` is an `int` pointer too. So, `*k = &a;` assigns an `int *` to an `int *`. Now, in the calling code, we have `int *j`, so it is an `int` pointer. Therefore, `&j` is an `int **` and can be passed to the function. So, everything ties up. Of course, once the function returns, the pointer stored in `j` is no longer valid because the function returned. Fortunately, the code doesn't use the value. – Jonathan Leffler Oct 04 '14 at 05:29
  • @user3867445 Yes, @JonathanLeffler is absolutely correct. `**k` is not `&j` at all. Probably you are thinking that because the function goes like `fun(int **k)`. That is not true. Well, think of this situation as, "`fun` is being passed the address of an `int` pointer j in main()" and "`fun` takes a pointer-chain as argument"(this is also called multiple indirection). Maybe that will prevent you from going too visually. Different things work for different people. Keep experimenting with pointers. Pointers, though a little complicated, are very very powerful. Good Luck! – Shravan Oct 04 '14 at 07:37