Here in this sample program to illustrate this behavior of strcpy()
,I wrote a string "S"
into a bigger string previous
which original had "Delaware"
.But this overwriting only affects the first two characters in the original string.The rest of the original string continue to have the same values.How to deal with this? (Even memcpy()
seems likely to have the same behavior).I mean, how to turn the remaining characters into 0
?Or the rest of the characters in the string retaining their original values has no side-effects?
#include<stdio.h>
#include<string.h>
int main()
{
char previous[10]="Delaware";
printf("The character at position 4 is %c\n",previous[4]);
strcpy(previous,"S");
printf("The character at position 4 later is %c",previous[4]);
}
The strcpy function does this:
previous "S"
| |
v v
-- -- -- -- -- -- -- -- -- -- -- -
| D| e| l| a| w| a| r| e|\0| | | S|\0|
-- -- -- -- -- -- -- -- -- -- -- --
^ ^ | |
| | | |
| - - - - - - - - - - - - - - - -
|_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _|
leaving your memory looking like this:
-- -- -- -- -- -- -- -- -- -- -- -
| S|\0| l| a| w| a| r| e|\0| | | S|\0|
-- -- -- -- -- -- -- -- -- -- -- --
The extra characters after the 0 will not matter when referring to previous in things like printf. Just like the extra memory location after the 0 in Delaware didn't affect your using previous when referencing it.