Initializing Dynamically allocated integer

Viewed 53

I guess dynamically created variable has to be initialized separately and not at the time of allocating. Why the below line of code does not compile? Why do I get the error message " expected ')' before 'p'".

*(int *p = malloc(sizeof(int))) = 23;

|

2 Answers

The definition int *p cannot appear inside an expression, it is a syntax error. You must use a definition and a separate expression to initialize the contents:

int *p = malloc(sizeof(int));
*p = 23;

or

int *p;
*(p = malloc(sizeof(int))) = 23;

Note that both of the above forms have undefined behavior in case of memory allocation failure.

This

int *p = malloc(sizeof(int))

is a declaration of the variable p.

You may not use declarations like an expression.

So you need to split this line

*(int *p = malloc(sizeof(int))) = 23;

in two lines like

int *p = malloc(sizeof(int));

and

*p = 23;

Another way is at first to declare the variable p

int *p;

and then to use the declared variable in the expression

*( p = malloc( sizeof( int ) ) ) = 23;
Related