Modification through pointer fails

Hi,all.
Please read my code which is quite simple.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;
void st(char* q)
{
*q = 'x';   //the problem goes here
cout<<q;
}
void main()
{
char *p;
p = "abc";
st(p);
cout<<p;
}

when i run this programme,i got a run-time error,saying that a address can not

be written(from my debugger ,i can tell it is the base address

of "abc"
),so, what is the matter, i just pass a string pointer paramenter to the function,called

by value,and try to modified the string contents a little bit through my string

pointer,how come this be incorrent,i mean the reason and how to fix it !

Thanks in advance!
Last edited on
Ok, on line 11, you assign p to be the address of the constant char* "abc". Then, inside the function, you attempt to modify that to become 'x', which is impossible, since "abc" is in read-only memory. You would either a) need to use dynamic allocation to create your C-string, or b) use an std::string and not have to worry about this kind of stuff.
Gotcha ,many thanks!
Topic archived. No new replies allowed.