By silent1mezzo
via easyctutorials.com
Published: Oct 31 2007 / 11:27
One of the hardest concepts in the C programming language for me is Pointers. To this day I still often have to look into my text books when I’m diving deep into pointer world. This tutorial is helpful for beginners.
Comments
mjanssen replied ago:
Seems there are still some mysteries remaining. Several remarks:
#include >stdio.h
p = &x;
p is not declared, this should be ptr = &p;
"you could also use *ptr here because the scanf puts the value into x’s memory location"
No you can't you can put ptr here. ptr contains the address of x, *ptr is the value of x.
free(*ptr);
Two remarks, if you want to free a piece of allocated code you want to free the address (ptr) not the value (*ptr). Secondly, you should only free memory allocated with malloc. So the free is completely unecessary in this discussion.
Also *ptr = NULL;
should be ptr = NULL; after free(ptr), *ptr=NULL; invokes undefined behaviour.
mjanssen replied ago:
Seems there are still some mysteries remaining. Several remarks:
#include stdio ?
surely you meant:
#include \
p = &x;
p is not declared, this should be ptr = &p;
"you could also use *ptr here because the scanf puts the value into x’s memory location"
No you can't you can put ptr here. ptr contains the address of x, *ptr is the value of x.
free(*ptr);
Two remarks, if you want to free a piece of allocated code you want to free the address (ptr) not the value (*ptr). Secondly, you should only free memory allocated with malloc. So the free is completely unecessary in this discussion.
Also *ptr = NULL;
should be ptr = NULL; after free(ptr), *ptr=NULL; invokes undefined behaviour.
Voters For This Link (7)
Voters Against This Link (0)