How to set char pointer as read-only pointer to a string in C++

1 Answer

0 votes
#include <iostream>
   
using namespace std;
   
int main() {
    string s = "c c++ java php"; 
  
    const char *p = s.c_str();
      
    s[0] = 'Q';
     
    // p[1] = 'Q';  // error: assignment of read-only
    // *(p + 1) = 'Q'; // error: assignment of read-only
       
    for (int i = 0; i < s.length(); i++) { 
        cout << p[i] << endl;
    } 
}
   
   
   
/*
run:
   
Q
 
c
+
+
 
j
a
v
a
 
p
h
p
   
*/

 



answered Aug 10, 2019 by avibootz

Related questions

2 answers 230 views
230 views asked Aug 10, 2019 by avibootz
3 answers 509 views
2 answers 201 views
1 answer 165 views
...