There are a number of problems in the first example.
As the compiler message indicates,
| deprecated conversion from string constant to 'char*' |
there is a problem with the declaration here:
|
char *salute = "I love you Greetings," ;
|
Basically the literal
"I love you Greetings," is read-only. That means you cannot change the contents of the string later. To properly write that line, the pointer should be declared as constant:
|
const char *salute = "I love you Greetings," ;
|
So far, so good. But now what about this line,
|
salute = '\0'; // Assigning the null character to *salute
|
Well, the comment says you want to assign a null character in the location pointed to by
salute. But that isn't what the code does, Instead, it alters the pointer itself and sets it to zero. Effectively that is now a null pointer, it doesn't point to anything at all.
But, when the code is corrected,
|
*salute = '\0'; // Assigning the null character to *salute
|
the compiler now gives the error message,
[Error] assignment of read-only location '* salute' |
So where to go from here? Well since you want to modify the contents of the string, don't declare a pointer to a read-only literal. Instead, declare a character array:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include <iostream>
using namespace std;
int main()
{
char salute[] = "I love you Greetings," ;
cout << salute << endl ;
*salute = '\0'; // Assigning the null character to *salute
cout << salute;
}
|
Notice at line 10, even though salute is an array, it is interpreted here as a pointer to the start of the array.