assign to char * array

I was trying to assign a value to a single element of char * array but, for some reason the window crashes every time I use the
assignment operation a[0] = 't' and when using a[0] = "t" the compiler trows an error something like invalid conversion from const char* to char
Can anyone help?
1
2
3
4

 char * a = "some text"; // ok!
 a[0]='k';               // doesn't work<<
 cout<<a[0];             // ok! 
Considering this part of the code:

char * a = "some text";

You must understand that a is a pointer, not an array.
A pointer holds a memory address (which is a number).
"some text" is what's called a string literal. It is a nameless, read-only char array.

So the correct definition of a would actually be:

1
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 "some text", but you may not change its contents.

With that out of the way, you probably wanted to define a char array.

1
2
char a[] = "some text";
a[0] = 'k'; // now works 


This time a is a real array.
The string literal "some text" is used to initialize the contents of the array, contents which can be changed.

http://en.cppreference.com/w/cpp/language/expressions#Literals
Topic archived. No new replies allowed.