Why is the following C code illegal?

Consider a typical environment, why is the following code invalid in C?

{
int x;
&x = (int*) malloc(3*sizeof(int));
...
}
+3
source share
7 answers

You cannot assign an address xbecause the address is xnot an lvalue

(Of An lvalue- is "something that can be assigned", ie it can not be of L eft side of the equals sign)

Try

int* x;
x = (int*) malloc(3*sizeof(int)); // TODO: Call free(x) 

Now xpoints to the allocated memory, and you can do something like

int foo = *x;
int bar = x[0];

You can assign an address to xanother using the operator &as follows:

int x = 1;
int* y = &x;  // y now holds the address of x
*y = 2;       // Now x = 2
+31
source

x lvalue - , . C , , - addreses.

+11

. X . , : ", , , , " x ".

int main()
{
    int* x;
    *(&x) = malloc(3*sizeof(int));

}
+3

. , , - :

int *x = (int *)malloc(3 * sizeof(int));
...
free(x);
+2

& x x. , .

- , , int * x;

+1

, , ( , , , , , ).

x . malloc . , -, , - , , .

, - 3 * sizeof (int). , , 1 int, 1 * sizeof (int), .

+1

The way the language is designed. Use the pointer to do what you want.

0
source

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


All Articles