howa wrote:
>
> Kai-Uwe Bux ???
>
>> howa wrote:
>>
>> >
>> > xhy_China ???
>> >
>> >> you can replace the following sentence
>> >> char *str = "apple";
>> >> by char str[]=""apple;
>> >
>> > that great! thanks....
>> >
>> > btw, what is the difference ?
>> >
>> > char *str = "apple";
>> > char str[] = "apple";
>> >
>> > both `str` are pointer to the beginning to the string, isn't?
>>
>> Nope: the first is a char* that points to the first character of a string
>> literal (which is constant and that causes the UB you experienced). The
>> second is an array of char that has been initialized to contain
>>
>> { 'a', 'p', 'p', 'l', 'e', 0 }
>>
>> This array is not declared const and you can modify the contents
>> (although you cannot change its address or length). The two critters are
>> of utterly different type and assignments only work one way:
>>
>> #include <iostream>
>>
>> int main ( void ) {
>> char * c_ptr = 0;
>> char c_arr [] = "apple";
>> c_arr = c_ptr; // fails to compile!
>> c_ptr = c_arr; // works: c_ptr now points to c_arr[0].
>> std::cout << c_ptr << '\n';
>> }
>>
>>
>>
>> Best
>>
>> Kai-Uwe Bux
>
> so is that mean
>
> 1. if i do not want to modify the value
>
> char *str = "apple" or char str[] = "apple"
>
> the usage dose not matter, the pointer can be used in the same way
If you do not want to modify, you should use const:
char const * c_ptr = "apple";
char const c_arr [] = "apple";
> 2. if i want to modify the value, i need to use char[]
If you want to modify, you should use std::string.
Actually, you should use std::string anyway:
std::string const banner = "apple";
std::string buffer = "apple";
Is there a reason that you want to make your life harder and your code less
efficient by using char* or char[]?
Best
Kai-Uwe Bux
|