char array Q

S

suresh shenoy

I know that
char s[100];
s = "xyz";
is invalid and should use char ptr or string library to store a string
literal in s. Can anyone be precise why the second line is invalid?
 
R

Richard Heathfield

suresh shenoy said:
I know that
char s[100];
s = "xyz";
is invalid and should use char ptr or string library to store a string
literal in s. Can anyone be precise why the second line is invalid?

The assignment operator requires as its left operand a modifiable lvalue.
Arrays are not modifiable lvalues.

Initialisation with a string literal is, however, permissible:

char s[100] = "xyz";

The contents of s are now 'x', 'y', 'z', and 97 '\0's.
 
V

vippstar

suresh shenoy said:
I know that
char s[100];
s = "xyz";
is invalid and should use char ptr or string library to store a string
literal in s. Can anyone be precise why the second line is invalid?
char s[100] = "xyz";

The contents of s are now 'x', 'y', 'z', and 97 '\0's.

Just wanted to mention why this happends;
In array initialization, when the initialization does not initialize
all the elements of the array, the rest are given the value 0 (or NULL
in pointer context)
Notice, I said the rest; which means int foo[3] = { [1] = 42 };
guarantees foo[0] to be 0.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top