problem with void pointer

Hi,

I just wrote a simple program, but it is not working as expected..
1
2
3
4
5
6
7
8
#include <stdio.h>
main()
{
void *p;
char chr[]= {"Harry Potter"};
p=(char*)chr;
printf("%c",(char *)p);
}

Why it is not printing "H" here ? Is it not supposed to print letter H ??
You have to dereference the pointer.
Can you provide some hint on it ??

I have tried with

1
2
3
p=(char*)&chr;
printf("%c",(char *)p);
}
too

It doesn't work either
1
2
3
4
5
6
7
8
#include <stdio.h>
int main() // Don't forget the int part, not all compilers will automatically add it
{
   void *vp;
   char chr[] = {"Harry Potter"};
   vp = (char*)chr;
   printf("%c",*vp);
}
Last edited on
Except you can't dereference a void pointer.

1
2
3
4
5
void *p;
char chr[]= {"Harry Potter"};
p=chr;
printf("%c",*(char *)p);
}


Note on line 4 you have to cast to a non-void pointer (in this case a char pointer), then you dereference the pointer with *.

Of course you could just get rid of the useless void pointer and use chr directly:

1
2
char chr[]= {"Harry Potter"};
printf("%c",*chr);   // or chr[0] 


void pointers are evil.
Haven't worked with them for a while, forgot how to use them, Disch is indeed right. Although, void pointers can be useful when working with threads; to interchange data between the two threads you need a void pointer.
Topic archived. No new replies allowed.