I started reading Pointers and while tinkering with them. I stumbled upon this :
#include<stdio.h>
int main()
{
int *p,a;
a=sizeof(*p);
printf("%d",a);
}
It outputs : 4
Then in the place of sizeof(*p)
I replaced it with sizeof(int*)
Now it outputs 8 .
P is a pointer of integer type and int* is also the same thing ( Is my assumption correct? ). Then why it is printing two different values. I am doing this on a 64bit gcc compiler.
Usually it depends upon the word size of underlying processor for example for a 32 bit computer the pointer size can be 4 bytes for a 64 bit computer the pointer size can be 8 bytes. So for a specific architecture pointer size will be fixed. It is common to all data types like int *, float * etc.
int means a variable whose datatype is integer. sizeof(int) returns the number of bytes used to store an integer. int* means a pointer to a variable whose datatype is integer. sizeof(int*) returns the number of bytes used to store a pointer.
No, it is not correct. The size of an int and the size of a pointer vary across platforms, and they are not necessarily the same. Indeed, on modern 64-bit consumer hardware, you're likely to find 32-bit int s and 64-bit pointers.
Every beginner always gets confused with pointer declaration versus de-referencing the pointer, because the syntax looks the same.
int *p;
means "declare a pointer to int". You can also write it as int* p;
(identical meaning, personal preference).*p
, when used anywhere else but in the declaration, means "take the contents of what p points at".Thus sizeof(*p)
means "give me the size of the contents that p points at", but sizeof(int*)
means "give me the size of the pointer type itself". On your machine, int
is apparently 4 bytes but pointers are 8 bytes (typical 64 bit machine).
*p
and int*
are not the same things! First one is a dereferenced pointer (i.e. int
which is 4 bytes wide) and the second one is a pointer (8 bytes wide in your case since it's a 64 bit machine).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With