Reputation: 33
It's simple question but i just couldn't figure out. I've been trying to make an approach to replace the content of one string by part of it's content like, replace "He is a boy" to "is a boy" as follow:
int main() {
char array[] = "he is a boy";
strcpy(array, &array[3]);
printf("%s\n", array);
}
But the program just stopped at strcpy statement. Is there any problem using strcpy or any other method to achieve the same purpose?? BTW, I'm using X-code on my mac. Thx~
Upvotes: 0
Views: 64
Reputation: 399803
Yes, you cannot use strcpy()
when the source and destination overlap. This is clearly stated in the manual page:
The strings may not overlap, and the destination string dest must be large enough to receive the copy.
You can use memmove()
, but then you have to specify the length and probably deal with termination issues yourself since it's a general-purpose memory-manipulation function, and not designed for strings specifically.
In your case since you're copying the tail, we can just include the termination and be fine:
int main(void) {
char array[] = "he is a boy";
memmove(array, array + 3, 9);
printf("%s\n", array);
return 0;
}
Upvotes: 3