pauk
pauk

Reputation: 408

Why are pointer type casts necessary?

I cannot understand why are pointer type casts necessary, as long as pointers point to an address and their type is important only when it comes to pointer arithmetic.

That is to say, if I encounter the next code snippet:

int a = 5; then both

char*b = (char*)&a; and int*c = (int*)&a

point to the very same memory location.

Indeed, when executing char*b = (char*)&a part of the memory contents may be lost, but this is due to the type of b is char* which can store only sizeof(char) bytes of memory, and this could be done implicitly.

Upvotes: 0

Views: 469

Answers (3)

The type of the pointer is most important when you dereference the pointer.

The excerpt

char *b = (int*)&a;

is wrong because int * cannot be assigned to char *. You meant char *b = (char *)&a;. The C standard says you need an explicit cast because the types are not compatible. This is the "yeah yeah, I know what I am doing".

The excerpt

int*c = (int*)&a;

is right, but &a is already a pointer to an int, so the cast will do no conversion, therefore you can write it as int *c = &a;.

Upvotes: 1

IrAM
IrAM

Reputation: 1738

as long as pointers point to an address and their type is important only when it comes to pointer arithmetic.

No, not only for pointer arithmetic. Its also important for accessing the data pointed by the pointer, the wrong way of accessing as in your example leads to improper results.

when executing charb = (int)&a part of the memory contents may be lost, but this is due to the type of b is char* which can store only sizeof(char) bytes of memory,

First of all, that is wrong to do (unless we really need to extract 1-byte out of 4-bytes)
Second, the application of pointer cast is mostly used w.r.t void*(void pointers) when passing data for a function which can handle many different type, best example is qsort

Upvotes: 1

Barmar
Barmar

Reputation: 781716

The pointer type is important when you dereference it, since it indicates how many bytes should be read or stored.

It's also important when you perform pointer arithmetic, since this is done in units of the size that the pointer points to.

Upvotes: 3

Related Questions