C++ replace char value to a pointer questions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
using namespace 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;    
}



Segmentation fault (core dumped)
Last edited on
Change this line

char *ary = "Apple, peter, pen";

to

char ary[] = "Apple, peter, pen";
i ve got the correct output !! Thx a lot !
but i would like to know why i can not use *ary to output the correct ans ??
Line 24 should really have been const char *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.
When the compiler encounteres this line

char *ary = "Apple, peter, pen";

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.
Last edited on
vlad from moscow wrote:
The C++ Standard allows to omit the qualifier for compatibility with old code.
This was changed in C++11.
Topic archived. No new replies allowed.