-1

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.

3 Answers3

2

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.

Zan Lynx
  • 53,022
  • 10
  • 79
  • 131
1

Because alldevsp is an output parameter, that is a parameter that will be used to return a value from a function (pcap_findalldevs) to the caller (your code).

In order to achieve that, the parameter should be passed by reference and since there is no such thing as reference in C, a pointer is used.

To summarize: the library uses the pointer that you've provided to know where to write the data that's why you need to pass a pointer to an already existing variable.

r3mus n0x
  • 5,954
  • 1
  • 13
  • 34
0

Because you have to pass a pointer to something and that something is dvs which has type pcap_if_t*. The type of that pointer is pcap_if_t**. When you delare pcap_if_t** dvs, and pass &dvs, you are passing a pcap_if_t***, which is not the expected type.

If you had:

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

Then dvs would have the expected type but would point to noting valid (unitialised).

For pcap_findalldevs() specifically, the function modifies the value of dvs, for that to happen, it must have a pointer to it, not just a copy of it - modifying the copy will not result in dvs being modified - it must be done by reference.

Clifford
  • 88,407
  • 13
  • 85
  • 165