I'm learning c by reading K&R and doing the exercises. I'm now in chapter 5 which deals with pointers. I don't understand why the statement:
int *p;
is not:
long int *p;
since *p contains an address and there is no guarantee that a variable of type int will be large enough to hold a large address. Or is there?
int is the type of the object that the pointer points to and not the size of the pointer itself. The size of the pointer is independant of the object it points to
For example:
int *p;
double *d;
Both pointers
p and d would "normally" have the same size, but the data that they point to don't have the same size.
Edit: As pointed out in the comments pointers aren't actually "required" to be of the same size.
As John explained:
For instance, a char * on a word-addressed system may actually be larger than an int *, since it needs to specify an offset into the word. The only guarantees are that void * and char * have the same alignment and representation, that pointers to compatible types have the same alignment and representation, that pointers to struct types have the same alignment and representation, and pointers to union types all have the same alignment and representation
long int *
means a point to a long int
.
It doesn't mean a long pointer.
Pointers are separate things and will have their own size. (dependent on the bitness that you're compiling for)
int *
is not of type int
. It is a pointer type. Therefore it will be large enough to store any address. long int *
is the same size as int *
-- it's just that you're treating where things are pointed to as different.
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