fork download
  1. #include <stdio.h>
  2. int main(){
  3. int* pointerToInt=NULL; //This DECLARES a pointer to an int and assigns the address stored in the poitner as NULL (0)
  4. int a=40; //This is just an int with value 40, not a pointer
  5. int b=0; //just another int with value 0, not a pointer
  6. float myFloat=1.0f; //just a float, not a pointer
  7. printf("We're on line#%d and a is:%d\tb is:%d \n",__LINE__, a, b);
  8. //a=*pointerToInt; //this would dereference (take the value that pointerToInt points to)
  9. //and assign it to a, but I've commented it out because i'd be dereferencing null, which isn't allowed (on normal platforms)
  10. pointerToInt=&a; //This takes the ADDRESS to a, you can now say that "pointerToInt points to a" meaning that:
  11. b=*pointerToInt; //If we dereference it we will get the value that is contained in a
  12. printf("We're on line#%d and a is:%d\tb is:%d \n",__LINE__, a, b);
  13. void* pointerToVoid=NULL; //This is a pointer to void type. A void type doesn't have a size, so it's just an address
  14. pointerToVoid=&a; //we can store any address in a void pointer but:
  15. //b=*pointerToVoid; //This doesn't workbecause the pointer isn't specified to point to a complete object type (a struct, a primitive like float, int whatever)
  16. a=5; //Just to make some change
  17. printf("We're on line#%d and a is:%d\tb is:%d \n",__LINE__, a, b);
  18. b=*((int*)pointerToVoid); //We can do this to make this work. We coerce/cast the void* to be an int*. It now makes sense to dereference it.
  19. //(The outermost parenthesis here is uneccesary but I added it for some clarity)
  20. printf("We're on line#%d and a is:%d\tb is:%d \n",__LINE__, a, b);
  21. pointerToVoid=&myFloat; //since this is a void pointer we can take the address of a float and store it in a void pointer without the compiler complaining
  22. b=*((int*)pointerToVoid); //we can then dereference it as an int, which doesn't make much sense at all
  23. printf("We're on line#%d and a is:%d\tb is:%d \n",__LINE__, a, b); //This happens. Be careful using void pointers.
  24. return 0;
  25. }
Success #stdin #stdout 0s 9432KB
stdin
Standard input is empty
stdout
We're on line#7 and a is:40	b is:0 
We're on line#12 and a is:40	b is:40 
We're on line#17 and a is:5	b is:40 
We're on line#20 and a is:5	b is:5 
We're on line#23 and a is:5	b is:1065353216