Why is a temporary char** argument illegal?

  • A+
Category:Languages

I have a function, f(char **p), and I wanted to call it in the simplest way I could.

I tried

char ** p = {"a", "b"}; f(p); 

and got:

scalar object requires one element in initializer

so I changed it into

char * p[2] = {"a", "b"}; f(p); 

and that went fine [would have been also fine with just char * p[]].

Why can't I create an array of pointers on the fly like the following?

f({"a", "b"}); 

 


This gives a warning:

char ** p = {"a", "b"}; 

because p is not an array.

This is also not legal:

f({"a", "b"}); 

since curly braces by themselves are not allowed in an expression (but can be used as an initializer).

It is possible to create an array on the fly like that using a compound literal:

f((char *[]){"a", "b"}); 

You could also use a compound literal to initialize a temporary:

char ** p = (char *[]){"a", "b"}; 

Unlike the first statement, this is valid because the literal is an array of type char *[2] and will decay to a char ** which can be used to initialize a variable of this type.

See section 6.5.2.5 of the C standard for more details on compound literals.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: