#include <iostream>
usingnamespace std;
int replace(char *ptr, char c1, char c2);
int replace(char *ptr, char c1, char c2){
int count = 0;
int i = 0;
while(*(ptr+i)!='\0'){
if(*(ptr+i) == c1){
*(ptr+i) = c2; // I can not replace the value to this ptr , if i remove this statement, the program can count how many p on ary
count++; // This program could count how many 'p' on ary
}
i++;
}
return count ;
}
int main(){
char *ary = "Apple, peter, pen";
cout << "Count : " << replace(ary, 'p', 'q') << endl;
cout << ary << endl;
return 0;
}
Line 24 should really have been constchar *ary = "Apple, peter, pen"; because you are not allowed to write to the array that the string literal gives you.
char ary[] = "Apple, peter, pen"; This makes ary an array instead of a pointer. The content of the string literal will be copied to ary, so you can modify the elements of ary all you want.
it does two things. Firstly it allocates memory for string literal "Apple, peter, pen". It has type const char[18], that is it may not be changed. Then the compiler initializes the pointer by the address of the first character of the string literal. The correct declaration shall look as
const char *ary = "Apple, peter, pen";
The C++ Standard allows to omit the qualifier for compatibility with old code base.