Can someone explain why this simple ternary operation won’t even compile, in C?
void main(int argc, char *argv[]){
int a = atoi(argv[1]);
char foo[] = (a == 1) ? "bar1" : "bar2";
}
It seems to be a problem with strings in particular.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
A string literal
"bar", when used in an expression (in this case, inside the ternary operator), is a pointer to pre-allocated memory. You cannot initialize an array using a pointer to data, only using a literal ("..."or{...}).Instead, you could assign it to a
char *:This will not make a copy of the literal but point to it, so you should not modify the elements of
foo. If you need a copy, you can usememcpy, provided that you know how big to declare the array:If you particularly want to be able to assign the contents, then there is a trick to doing that; it is possible to implicitly copy the contents of a
structusing assignment (as well as returning it from a function, and so on), no matter what thestructcontains, and you could put a character array in astruct:Just like the second option, when you do this you have to pick a fixed size for the array in the
structdeclaration. If you have strings of unbounded length, then you must use pointers.