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

Very new to C here, and I think I barely understand the concept of pointers, but the syntax is a bit confusing, so it's hard for me to understand what this expression means x = (char *) &a;.

The rest of the function is 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; 
}

In particular, why write x = (char *) &a;instead x = &a;? What adds added (char *)to change the expression?

+4
source share
2 answers

This is a cast . It tells the compiler what it should interpret &aas a char*instead int*, which is its actual type.

, , , " , , , char*", X, Y.

X Y Y , char*. .

int ( x[]), , ( ).

+8

. .

:

x = &a;

int * a char *. , , .

. :

 x = (char *) &a;

&a, int *, char *. x .

undefined , char *, , . char *, . , , undefined .

+3

Source: https://habr.com/ru/post/1694648/


All Articles