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

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

So, I want to confirm the following two things:

  • So, suppose I'm on a 32-bit machine, then this means that the memory addresses are 32 bits wide. So the size of char * and int * is 32 bits (4 bytes), right? Also char * * size also matches int * size?

  • Suppose I have: int * ptr;

So now executing * ((char * *) ptr) = 0x154 is the same as * ((int *) ptr) = 0x514 is the same, right? (0x514 is any random memory address)

Platform: I am on x86.

PS: I know that type casting is not a suggested coding method. But I do kernel coding, so I need to do the casting!

+7
source share
2 answers

In C pointers, the same size is not guaranteed . Now, in fact, most implementation pointers will be the same size, but this is a detail of the compiler implementation.

From C Faq :

The old HP 3000 series uses a different addressing scheme for the address byte than for word addresses; as several machines are higher so it uses different representations for char * and void * than for other pointers.

Depending on the β€œmemory” model used, 8086-family processors (PC compatible devices) can use 16-bit data pointers and a 32-bit pointer function, or vice versa.

Also *((char *)ptr) = 0x154 does not match *((int *)ptr) = 0x154 . Since you are looking for a pointer, you will write data of size char and size int to the location pointed to by ptr . Suppose that an 8-bit char and a 32-bit int, *((char *)ptr) = 0x154 will write 0x154 to the memory address assigned by ptr , and *((int *)ptr) = 0x154 will write 0x0000000154 in 4 bytes, starting at the address assigned to ptr .

+11
source

Technically speaking, the C standard ensures that sizeof (char) == 1 and the rest is up to implementation. But on modern x86 architectures (e.g. Intel / AMD chips) this is pretty predictable.

You have probably heard that processors are described as 16-bit, 32-bit, 64-bit, etc. This usually means that the processor uses N-bits for integers. Since pointers store memory addresses and memory addresses are integers, this effectively tells you how many bits will be used for pointers. sizeof is usually measured in bytes, so code compiled for 32-bit processors will report the size of pointers 4 (32 bits / 8 bits per byte), and code for 64-bit processors will report the size of pointers 8 (64 bits / 8 bits) per byte). In this case, the limitation of 4 GB of RAM for 32-bit processors comes from - if each memory address corresponds to a byte, to access more memory you need integers in excess of 32 bits.

In practice, pointers will be size 2 on a 16-bit system (if you can find it), 4 on a 32-bit system and 8 on a 64-bit system, but nothing will come of using the given size

+1
source

All Articles