Midas
Midas

Reputation: 7131

Char array declaring problems

Why can I do

char identifier[4] = {'A', 'B', 'C', 'D'};

and not

char identifier[4];
&identifier = {'A', 'B', 'C', 'D'}; // syntax error : '{'

?

And why can I do

char identifier[4] = "ABCD"; // ABCD\0, aren't that 5 characters??

and not

char identifier[4];
&identifier = "ABCD"; // 'char (*)[4]' differs in levels of indirection from 'char [5]'

?

Is this a joke??

Upvotes: 0

Views: 371

Answers (3)

Clifford
Clifford

Reputation: 93476

Three points:

  • Initialisation is not assignment

  • Arrays are not first-class types so cannot be assigned. You have to assign the elements individually (or use a function such as strcpy() or memcpy().

  • The address of an array is provided by the array name on its own.

In your last example, the following is a valid solution:

char identifier[4];
memcpy(identifier, "ABCD", sizeof(identifier) ) ;

You cannot use strcpy() here, because that would require an array of 5 characters to allow for the nul terminator. The error message about levels of indirection is not a "joke", it is your error; note in the above code identifier does not have a & operator, since that would make it a char** where a char* is required.

Upvotes: 2

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272497

What Arkku said, but also, you cannot assign to the address of something, i.e. &x = ... is never legal.

Upvotes: 2

Arkku
Arkku

Reputation: 42139

You can only initialize the array when you declare it.

As for char identifier[4] = "ABCD", this is indeed possible but the syntax is used to deliberately omit the trailing NUL character. Do char identifier[] = "ABCD" to let the compiler count the characters and add the NUL ('\0') for you.

Upvotes: 3

Related Questions