I am trying to implement a simple string copy in the following code.
However, I got a run-time error in the line “*d = *c;”.
Could anyone tell me what is wrong with that?
void test3()
{
char *a="123456";
char *b="000000";
char *c=a;
char *d=b;
while(*c){
*d = *c;
cout << *c << endl;
c++;
d++;
}
*d='\0';
}
Basically, string litterals are constant and can’t be changed. In the following line:
char *ashould be replaced withconst char * abecauseapoints to a block of constant memory. Further down the function, you attempt to change that block of constant memory and this yields a run-time error.To get a real character array that you can use in such a function, you should use:
This will produce a mutable (non-const) array that you can manipulate freely.