Hello when Im trying to learn strncpy function, I copied a part of string to another char array, but it gave me different results when I used puts and printf functions. Can anyone tell me why such difference occurs? I guess its about the last terminating NULL character, but Im not sure at all. Here is the code :

#include <stdio.h>
 #include <string.h>
 int main()
 {
         char a[] = "barbara dickens";
         char b[8];
         strncpy(b,a,7);
         puts(b);
         printf("%s", b);

        return 0;
 }

puts function prints barbara and printf function prints barbar,
Thanks

>Can anyone tell me why such difference occurs?
When printing a string (no format specifiers), the difference between puts and printf is that printf probably does more work for the same result. The reason is because printf needs to check for format specifiers while puts simply passes each character on to putchar. But your problem isn't related to which function you use for display.

>char b[8];
>strncpy(b,a,7);
>puts(b);

Your punishment is to write "I will null terminate all of my strings" 100 times on the blackboard. When you fail to end a string with '\0', garbage is usually the result. For example, running your program I get this:

barbara╠╠╠╠╠╠╠╠╠barbara dickens
barbara╠╠╠╠╠╠╠╠╠barbara dickens

strncpy is typically misunderstood because it doesn't really do what you would assume it's supposed to do, which is strcpy with a limit. Because of that, strncat is often preferred if you want a strcpy with a limit. Just set the destination as an empty string:

b[0] = '\0';
strncat(b, a, 7);

Or you could use strncpy and not forget to terminate the string:

strncpy(b, a, 7);
b[7] = '\0';

It's a subtle difference in this case, but I think significant enough to avoid bugs.

puts() adds a newline char to the end of the string. printf(), doesn't do that.

Best way to understand your code is to step through it with the debugger, and watch the value of b(). Then you can see exactly what strncpy() is doing.

The first 7 char's in a() are *not* a null terminated string - they're just 7 char's, and that's not the same thing, at all. With C if you want to deal with strings, you need to ensure that your would-be strings are always terminated with the end of string char: '\0'.

thank you, i have learned that i need to use null terminating character!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.