String literals manipulation - copying characters
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';
}
You cannot change const data. These strings you provide (literal strings) are stored in a read-only region of the program. In fact, any string literal you provide in your program, say "000000"
, is considered const char*
(pointer to const chars), so you are not allowed (not advised, at least) to modify them.
Basically, string litterals are constant and can't be changed. In the following line:
char *a="123456";
char *a
should be replaced with const char * a
because a
points 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:
char a[] = "123456";
This will produce a mutable (non-const) array that you can manipulate freely.
You are trying to modify a literal, which the compiler will generally place in a read-only part of the executable; modern processors have hardware locks to keep this from happening as an aid against viruses.
You can fix it by providing your own character array, which can be initialized with the literal:
char b[] = "000000";
Both *d=*c
and *d='\0'
are broken because you may not change these values that come from string literals. They are non-modifiable. If you'd used const
like you're supposed to, then you would have not made this mistake.
Since you have assigned both pointers c and d to constant strings, you can't change them! You would need to allocate a char array for d in order for this to work:
char d[MAX_CHAR];
精彩评论