Rainer Schmid
Rainer Schmid

Reputation: 1

String weirdness in C

I've just encountered a weird problem.

This code works:

int l = strlen(output); // l = 20 (believe me)
char withoutLeadingZeroes[20] = "";

and this doesn't:

int l = strlen(output); // l = 20 (believe me)
char withoutLeadingZeroes[l] = "";

I am getting this error

Array initializer must be an initializer list or string literal

I really don't get that. Any suggestions? Greetings from Vienna :-)

Upvotes: 0

Views: 3842

Answers (3)

John Bode
John Bode

Reputation: 123578

Online C99 Standard (n1256)

6.7.8 Initialization
...
3 The type of the entity to be initialized shall be an array of unknown size or an object type that is not a variable length array type.

The declaration char withoutLeadingZeroes[l] = ""; declares withoutLeadingZeros as a variable-length array, and attempting to initialize it as you're doing here is a constraint violation.

The diagnostic could be a bit clearer, though.

Edit

Can you point out exactly which line gets the error? I get a much clearer diagnostic with gcc, and I thought XCode ran gcc under the hood.

Upvotes: 1

Vinicius Kamakura
Vinicius Kamakura

Reputation: 7778

C doesn't support VLA (variable lenght arrays), maybe C99 onwards not sure in what C standard VLA got in.

suggestion:

int len = strlen(output);
char * wo_zeros = (char *)malloc(len);
strcpy(wo_zeros, "");
//do something with wo_zeros
free(wo_zeros);

Upvotes: 0

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39390

You can't initialize static array of any type in this way by using variable. It must be const, I believe.

VS2010: error C2057: expected constant expression

Upvotes: 2

Related Questions