Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does pointer type casting work in c

I understand that in c, a pointer points to a memory address. In the following code

char *cp;
someType *up; // Assuming that someType is a union of size 16 bytes
cp = sbrk(nu * sizeof(someType)); 

// Here is what confuses me
up = (someType *)cp;

According to this link http://en.wikibooks.org/wiki/C_Programming/Pointers_and_arrays

  1. If cp points to an address of 0x1234, so 0x1234 should be the beginning of the newly allocated memory, right?

  2. So when "cp" is casted to a pointer to someType and assigned to "up", it actually says "up" is a pointer that points to 0x1234, assumes in 32-bits system, each memory address takes 4 bytes, a someType object will use 4 memory address to store its value, so the addresses 0x1234, 0x1235, 0x1236, 0x1237 collectively store a someType object, is this correct?

Thanks in advance.

like image 522
AuA Avatar asked Dec 20 '22 01:12

AuA


2 Answers

Pointer type casting doesn't do anything at the machine level. The value in memory is still just a plain old value in memory.

At the language level, that value is used as an address. In other words it is often used as the value passed to operations that require memory locations, such as the assembly "load" operation.

At the language level, extra constructs are added to the machine operations, and one of those "extras" are data types. The compiler is responsible for checking if type-rule violations exist, but at run time there is not such a constraint.

As a result, the cast does nothing at run time, but at compile time it directs the compiler to not emit an error as the type of the pointer's value will now be considered a compatible type to the variable holding the address.

like image 53
Edwin Buck Avatar answered Jan 02 '23 12:01

Edwin Buck


Even on a 32-bit system, a memory address typically refers to a single byte, not four. So your Header will be covering the 16 memory addresses between 0x1234 and 0x1243.

like image 20
Vaughn Cato Avatar answered Jan 02 '23 12:01

Vaughn Cato