Alexey Pimenov
Alexey Pimenov

Reputation: 223

Char array declaration and initialization in C

I was curious about why this is not allowed in C:

char myarray[4];

myarray = "abc";

And this is allowed:

char myarray[4] = "abc";

I know that in the first case I should use strcpy:

char myarray[4];

strcpy(myarray, "abc");

But why declaration and later initialization is not allowed and declaration and simultaneous initialization is allowed? Does it relate to memory mapping of C programs?

Thanks!

Upvotes: 22

Views: 143158

Answers (5)

davep
davep

Reputation: 90

This is another C example of where the same syntax has different meanings (in different places). While one might be able to argue that the syntax should be different for these two cases, it is what it is. The idea is that not that it is "not allowed" but that the second thing means something different (it means "pointer assignment").

Upvotes: 1

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262919

That's because your first code snippet is not performing initialization, but assignment:

char myarray[4] = "abc";  // Initialization.

myarray = "abc";          // Assignment.

And arrays are not directly assignable in C.

The name myarray actually resolves to the address of its first element (&myarray[0]), which is not an lvalue, and as such cannot be the target of an assignment.

Upvotes: 41

Vlad
Vlad

Reputation: 35584

Yes, this is a kind of inconsistency in the language.

The "=" in myarray = "abc"; is assignment (which won't work as the array is basically a kind of constant pointer), whereas in char myarray[4] = "abc"; it's an initialization of the array. There's no way for "late initialization".

You should just remember this rule.

Upvotes: 5

pierre
pierre

Reputation: 9

myarray = "abc";

...is the assignation of a pointer on "abc" to the pointer myarray.

This is NOT filling the myarray buffer with "abc".

If you want to fill the myarray buffer manually, without strcpy(), you can use:

myarray[0] = 'a', myarray[1] = 'b', myarray[2] = 'c', myarray[3] = 0;

or

char *ptr = myarray;
*ptr++ = 'a', *ptr++ = 'b', *ptr++ = 'c', *ptr = 0;

Your question is about the difference between a pointer and a buffer (an array). I hope you now understand how C addresses each kind.

Upvotes: 0

Nofate
Nofate

Reputation: 2743

I think these are two really different cases. In the first case memory is allocated and initialized in compile-time. In the second - in runtime.

Upvotes: 0

Related Questions