assign to char * array
Mar 21, 2014 at 9:52am UTC
I was trying to
a value to a single element of char * array but, for some reason the
every time I use the
a = 't'
and when using a = "t" the compiler trows an error something like invalid conversion from const char* to char
Can anyone help?
2 3 4
char * a = "some text"; // ok!
a= 'k'; // doesn't work<<
cout<<a; // ok!
Mar 21, 2014 at 11:05am UTC
Considering this part of the code:
char * a = "some text";
You must understand that
is a pointer, not an array.
A pointer holds a memory address (which is a number).
is what's called a string literal. It is a nameless, read-only
So the correct definition of
would actually be:
2 const char * a = "some text";
// read as: `a` is a pointer to const char
You can take the memory address of the string literal
, but you may not change its contents.
With that out of the way, you probably wanted to define a
2 char a = "some text";
a = 'k'; // now works
is a real array.
The string literal
is used to initialize the contents of the array, contents which can be changed.
Topic archived. No new replies allowed.