Search code examples
cpcappointer-to-pointer

Why does a double pointer argument have to be declared as single pointer an passed as &var to the function?


Why does a double pointer argument have to be declared as a single pointer and passed as &var to the function?

I was wondering why I can't just declare a double pointer then pass it to a function, instead I first have to declare the pointer being pointed at before passing the double pointer.

This is shown for example when I run the argument **alldevsp I have to declare it as pointer and then pass its address to the function:

pcap_if_t *dvs;
int a = pcap_findalldevs(&dvs, errbuf);

However if I declare a pointer to a pointer like so:

pcap_if_t **dvs;
int a = pcap_findalldevs(dvs, errbuf);

It returns:

warning: ‘dvs’ is used uninitialized in this function [-Wuninitialized]

Segmentation fault (core dumped)

I was just wondering why declaring a variable as **var and passing it to a function does not work if I do not declare the pointer being pointed at beforehand.


Solution

  • The library wants a pointer to a pointer so that it can write into your pointer.

    That means that your program needs allocated memory for the pointer.

    The first example works because pcap_if_t *dvs; reserves some memory on the stack for a pointer. Then you pass the address of that memory into the pcap_findalldevs function.

    The second version fails because pcap_if_t **dvs does not point to real memory anywhere. The compiler even warns you about it being uninitialized.