0

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

Prag Rao
  • 1,411
  • 3
  • 11
  • 10

2 Answers2

2

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))));  
Community
  • 1
  • 1
Sadique
  • 22,572
  • 7
  • 65
  • 91
1

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.

jester
  • 3,491
  • 19
  • 30
  • how can i do the same in main funcion . if i want to assign double pointer to single pointer . without calling the function. – Prag Rao Oct 29 '13 at 05:19
  • you can do int ** p1 = &p. Then to get the value, you can dereference it twice like *(*p1). If you want to use void **, it should be void **p1=&p; and dereference should be the same : *((int *)*p1) – jester Oct 29 '13 at 05:23
  • @PragRao - `printf("Main %d",*((int *)*(( (void**)&p))));` – Sadique Oct 29 '13 at 05:23
  • void ** p1 = &p; // func((void**)&p); printf("Main %d",p[0]); printf("Func %d\n",* ((int*)*p1)); this gives error invalid conversion from int** to void** – Prag Rao Oct 29 '13 at 05:43
  • sorry for missing this out : void **p1 = (void **) &p; ( I missed the cast ) – jester Oct 29 '13 at 05:51