Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 961
doctopus Avatar asked Dec 18 '22 00:12

doctopus


1 Answers

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).

like image 185
Hatted Rooster Avatar answered Jan 04 '23 23:01

Hatted Rooster