Domanda

The double Pointer Manipulated. Suggest for workaround.

#include <iostream>
#include <stdio.h>
using namespace std;
/* Pointer Passed as argument */
void func(void **p1)
{
     printf("Func %d\n",*p1);
}
/* main Function */
int main()
{ 
 void **p1 = NULL;
 int *p = (int *)malloc(sizeof(int));
 p[0] = 20;
 func((void**)&p);//pass by address
 //How can we assign double pointer i.e (*p1 = &p)
 printf("Main %d",*p);   // print value
 cin.get();
 return 0;   
}
//function end main.cpp
/*
Func " Garbage value "
Main 20
*/

I am trying to use the double pointer to retreive data. Can someone look into this and let me know where is the bug.

output ahould be 20 - 20 Func 20 Main 20

È stato utile?

Soluzione 2

The printf in the function should be:

printf("Func %d\n", *((int*)*p1));

In the function, p1 has the address of the integer pointer int * p. This means dereferencing it once like *p1 is equivalent to the original pointer p. Hence we cast it to an int * and dereference it again to get the value.

Altri suggerimenti

This is what you need to do in func(void **p1):

printf("Func %d\n",*((int *)*p1));

You have to dereference it one more time to get the int value - since its a pointer-to-pointer.

And, do not cast the return of malloc (applicable only for C). In C++ the cast is required (better use the new operator).

In main you can directly do this:

  printf("Main %d",*((int *)*((  (void**)&p))));  
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top