Is size of char * same as size of int *?

user1599964 picture user1599964 · Feb 16, 2013 · Viewed 7.7k times · Source

I know: char * is a pointer to char. and int * is a pointer to int.

So, i want to confirm following two things:

  1. So now suppose I am on 32 bit machine, then that means memory addresses are 32 bit wide. Thus that means size of char * and int * is both 32 bits ( 4 bytes), right ? Also is size of char * * also same as size of int * ?

  2. suppose I have: int * ptr;

Thus now doing *((char * *) ptr) = 0x154 is same as *((int *) ptr) = 0x514 same, right ? ( 0x514 is just any random memory address)

Platform: I am on x86.

P.S.: I know type casting is not a suggested way to code. But I am doing Kernel coding, thus I HAVE TO do type casting !

Answer

shf301 picture shf301 · Feb 16, 2013

In C pointers are not guaranteed to have the same size. Now in reality most implementations pointers will be the same size, but that is an implementation detail of the compiler.

From the C Faq:

The old HP 3000 series uses a different addressing scheme for byte addresses than for word addresses; like several of the machines above it therefore uses different representations for char * and void * pointers than for other pointers

Depending on the ``memory model'' in use, 8086-family processors (PC compatibles) may use 16-bit data pointers and 32-bit function pointers, or vice versa.

Also *((char *)ptr) = 0x154 is not the same as *((int *)ptr) = 0x154. Because you are dereferencing the pointer you will write data the size of a char and the size of an int into the location pointed to by ptr. Assuming an 8 bit char and a 32 bit int, *((char *)ptr) = 0x154 will write0x154 to the memory address assigned to ptr and *((int *)ptr) = 0x154 will write 0x0000000154 to the 4 bytes starting at the address assigned to ptr.