Reputation: 141
I've just started to learn C programming. When coming to the String, I get confused with the function 'strcpy'. I tried switching places of first argument and the second argument. When I run the program, it just shows a 'S'. What does that mean?
char s2[ ]= "Hello";
char s1[10];
strcpy(s2, s1);
printf("Source string = %s\n", s2);
printf("Target string = %s\n", s1);
I thought the output would be null. But it just shows a 'S'.
Upvotes: 0
Views: 5102
Reputation: 37232
In C, strings are zero terminated. This means that an empty string is a string containing a single "zero terminator" char.
When an empty string is copied, the single "zero terminator" char is copied. The destination string still has an address (the "pointer to the strings chars" will point to the zero terminator) and the pointer to the string will not be NULL.
Upvotes: 0
Reputation: 223972
Based on the printf
statements, you have the arguments to strcpy
mixed up.
As it is now, you're copying s1
to s2
. The array s1
is uninitialized however, so the values it contains are indeterminate.
To copy s2
to s1
, switch the parameters:
strcpy(s1, s2);
If you leave it as is, you need to explicitly set s1
to an empty string to get consistent results.
char s1[10] = "";
Upvotes: 2