I wanted to get the first character of a string using strncpy, here's my code int main() {
char s[] = "abcdefghi";
char c[] = "";
printf("%c\n",c);
printf("%s\n",s);
strncpy(c,s,1);
printf("%c\n",c);
printf("%s\n",s);
return 0;
}
the problem is that c is still an empty string, what's wrong with it?
CodePudding user response:
The problem is that c
is an array (which decays into a pointer), while the %c
format of printf()
requires a character. If you pass the pointer when the function expects a character, you get undefined behavior, and a possible output will be the first byte of the address of the array, interpreted as an ASCII character.
Also, please note that char c[] = "";
simply declares an array of length 1 which contains the null (\0
) character. If you try to print that, like you do in your code, you will likely get weird output.
If c
is meant to only store a single character, declare it as a simple char
variable, and pass it's address to strncpy()
:
char s[] = "abcdefghi";
char c = ' ';
printf("%c\n", c);
printf("%s\n", s);
strncpy(&c, s, 1); //notice the & before c
printf("%c\n", c);
printf("%s\n", s);
However, you have to be careful. Passing any value greater than 1 to strncpy()
asks for big trouble, since you would be writing to an undefined location.
CodePudding user response:
s is an array of 10 chars, c is an array with one char. Do you understand why? And which char is stored in c?
%s is the format for strings, %c is the format for chars. But c is not a char. An array containing one char is an array, not a char. So when you try to print c you get rubbish.
Now the bad one: strncpy in your case doesn’t produce a C string because there isn’t enough space for one. If you try to print c with %c you get nonsense. If you try to print it with %s you get undefined behaviour. Do NOT use strncpy unless you really know what it is doing (you should generally avoid strncpy).