Hi, so that I could understand void pointers I created the following program:
Code:
#include <stdio.h>
#include <string.h>
int main(void) {
char word[] = "Zero";
int number = 0;
void *ptr = NULL;
printf("number = %d\t[%p]\n",number,&number);
printf("word = %s\t[%p]\n",word,&word);
/* Point to number. */
ptr = &number;
printf("*ptr = %d\t[%p]\n",*((int *)ptr),(int *)ptr);
/* Modify value of number. */
*((int *)ptr) = 1;
/* Point to word. */
ptr = &word;
printf("*ptr = %s\t[%p]\n",(char **)ptr,(char *)ptr);
/* Modify value of product */
strcpy(ptr,"One");
printf("number = %d\t[%p]\n",number,&number);
printf("word = %s\t[%p]\n",word,&word);
return 0;
}
The program works fine, however i really want to fully understand what is going on with the deferencing of the void pointer, for example:
With the following code:
Code:
ptr = &number;
*((int *)ptr) = 1;
Why can't you just do:
Code:
ptr = &number;
*(int *)ptr = 1;
And again with this code, (i'm guessing it's becuase its a pointer to a pointer?):
Code:
ptr = &word;
strcpy(ptr,"One");
Could someone please explain why this is neccessary or if you can point me at
an explaination I would be most grateful for any assistace.
Thanks
~P