Can't assign a pointer to primitive in C?

c, pointers

Solution

Several replies say that you can only take the address of named variables, but that's not entirely right: if you're using C99 or greater, you can also take the address of a compound literal or a field of a compound literal. Usually this is useful for e.g. calling a function that takes an in pointer to some struct, which you only need to create for the duration of the call. Example: `draw(&(struct point){ 5, 10 });`

Some avenues by which this could be used to obtain the address of a scalar [edited with explanations]:

// create a char array containing only 'a', dereference to get 'a', and take its address
char *c = &*(char[]){'a'};  

// same as above, but using an array subscript
char *c = & (char[]){'a'}[0];        

/* create a literal for one unnamed struct containing only the char member "c",
   access .c, and take its address all in the same statement */        
char *c = &(struct{char c;}){'a'}.c;

And for the duration of the containing block, *c will equal 'a'.

However the terser and more common way of obtaining an address to a literal using compound literals is simply to declare an array literal with only one element, which will decay to a pointer as usual on assignment:

char *c = (char[]){'a'};

And this is fairly typical syntax for the job. But as it turns out, the language allows us to do something even more direct and slightly unintuitive: we can declare a compound literal of a scalar type. Which reduces everything above to the more obvious:

char *c = &(char){'a'};

In your case,

#include <stdio.h>
int main(int argc, char const* argv[])
{
    char *str[3];
    str[1] = &(char){'a'};
    return 0;
}

It's a little more verbose than '&' and in fact only a few keys less than assigning a temp variable, but there it is.

Problem

I am wondering why this can compile: ``` #include <stdio.h> int main(int argc, char const* argv[]) { char *str[3]; char x = 'a'; char *px; px = &x; str[0] = px; return 0; } ``` while this cannot: ``` #include <stdio.h> int main(int argc, char const* argv[]) { char *str[3]; str[1] = &'a'; return 0; } decla.c: In function ‘main’: decla.c:9:14: error: lvalue required as unary ‘&’ operand ```

Original source