Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should int *p be long int *p instead?

Tags:

c

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?

like image 727
grok12 Avatar asked May 18 '11 21:05

grok12


3 Answers

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

like image 198
Pepe Avatar answered Sep 24 '22 00:09

Pepe


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)

like image 42
SLaks Avatar answered Sep 26 '22 00:09

SLaks


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.

like image 33
Billy ONeal Avatar answered Sep 25 '22 00:09

Billy ONeal