doctopus
doctopus

Reputation: 5657

What is the meaning of this expression (char *) in C?

Very new to C here and I think I just barely grasp the concept of pointers, but the syntax is a bit confusing so I'm having trouble trying to understand what this expression x = (char *) &a; means.

Rest of function for reference:

#include<stdio.h> 
int main() 
{ 
   int a; 
   char *x; 
   x = (char *) &a; 
   a = 512; 
   x[0] = 1; 
   x[1] = 2; 
   printf("%d\n",a);   
   return 0; 
}

More specifically, why is it necessary to write x = (char *) &a; instead of just x = &a;? What does the added (char *) do to alter the expression?

Upvotes: 4

Views: 1122

Answers (2)

dbush
dbush

Reputation: 223972

This is a type cast. It allows explicit conversion from one type to another.

If you just did this:

x = &a;

You would be trying to assign a int * to a char *. Converting between the two types is not normally allowed, and the compiler will typically give a warning if you do so.

The cast explicitly tells the compiler to treat an expression as a different type. In this case:

 x = (char *) &a;

The cast says to explicitly convert &a, which has type int *, to an expression of type char *. This expression can then be assigned to x with no warnings.

In most cases, converting from one pointer type to another invokes implementation or undefined defined behavior, however converting to a char * is allowed, as it allows you to access the individual bytes of a datatype consisting of multiple bytes. What you can't do however is use a char * which points to an object of a different type to write to that object. Doing so risks creating a trap representation, and subsequently attempting to read the original datatype would invoke undefined behavior.

Upvotes: 3

Hatted Rooster
Hatted Rooster

Reputation: 36483

It's a cast. It tells the compiler that it should interpret &a as a char* instead of a int* which is it's actual type.

Not making this cast would get you a compilation error as the types don't match, you're basically telling the compiler "I know what I'm doing and I'm sure this is a char*" thus allowing you to approach type X as if it was type Y.

Normally, casting a pointer of type X to Y and trying to dereference it through type Y would violate the strict aliasing rule but in this case because we're aliasing through char* it is allowed.

In this context it allows you to access the individual bytes of the int (by x[]), do note that the result will be different depending on the endianness of the machine (big or little).

Upvotes: 8

Related Questions