i have a question.
why do we need to declare pointers as int *p when int p also does the same work?
eg:
both give the same resultCode://eg1 int a=10, *p; p=&a; printf("%p", p); //eg2 int a=10, p; p=&a; printf("%p", p);
i have a question.
why do we need to declare pointers as int *p when int p also does the same work?
eg:
both give the same resultCode://eg1 int a=10, *p; p=&a; printf("%p", p); //eg2 int a=10, p; p=&a; printf("%p", p);
The 2nd example won't even compile. 'p' is an int, not a pointer to int.
There is a difference in the declaration of a pointer and the use of a pointer.
That may be where the confusion is. The '*' is used when declaring a pointer,
but not used when referencing the value of a pointer. The '*' is used when
dereferencing the pointer, to access what the pointer is pointing to.
In a declaration:
int p - is an int
int *p - is a pointer to int
In usage:
p is a pointer
*p is what p points to
Last edited by megafiddle; 11-24-2011 at 06:29 PM.
Although you can get the memory address just fine with this method, you wouldn't be able to dereference to get the value without declaring it as a pointer. With eg2 try changing the printf statement to:You will get a compiler error on this one, thus the value isn't retrievable and the pointer is pointless.Code:printf("%d", *p);
For most things you don't need pointers... in fact there is some wisdom in avoiding them as much as possible.
However, they do have their uses... For example I routinely deal with very large strings, text files loaded as one big piece, into memory that is allocated with malloc(). Then I will take with strtok() and build an array of pointers to the beginning of each line... None of it is the actual string but it does tell me where the strings are.
What a pointer does is allow you to store the address of something... not it's value, it's location... For example: "The house at 37 anystreet has a red door"... the pointer stores the address of the red door (37 anystreet) but not the red door itself. To see the red door you need to go to the address, or in computer terms you need to "dereference" the address to get at the data.
@megafiddle... The second example will compile and it will get the address of the data in a ... The integer variable p becomes just a number that happens to be the same as the address of a that will be utterly useless as a pointer.
Thanks for correcting.
My stuff fails to compile so often, that I don't distinguish between errors and warnings anymore..
But it all gets fixed in the end.
Last edited by megafiddle; 11-24-2011 at 06:48 PM.
thanks everyone!
especially Crptix for a lucid explanation. i'm just starting out so your simple was extremely helpful.