1833847 Members
2334 Online
110063 Solutions
New Discussion

Re: strncpy's problem

 
Xiaoming Zhang
Contributor

strncpy's problem

I ran the following c code:

#include
#include
main(){
char str1[50]="aaaaaaaaaa", str2[50]="bbbbbbbbbbb", str3[50]="ccccccccccccc",str4[50];

strncpy(str4,str2,8); printf("str4 is %s \n", str4);
strncpy(str4,str3,4); printf("str4 is %s \n", str4);
strncpy(str4,str1,8); printf("str4 is %s \n", str4);
strncpy(str4,str3,4); printf("str4 is %s \n", str4);
}

and got following output:
str4 is bbbbbbbb
str4 is ccccbbbb
str4 is aaaaaaaa
str4 is ccccaaaa

However, I acutally want to get output like this:
tstr4 is bbbbbbbb
str4 is cccc
str4 is aaaaaaaa
str4 is cccc

What should I do to get the output I want?

Thanks!


4 REPLIES 4
Patrick Wallek
Honored Contributor

Re: strncpy's problem

I haven't got a whole lot of experience with C, but I would say you should probably set your str4 to a null in between copies. I think that will then give you the results you are looking for.
Dan Hetzel
Honored Contributor

Re: strncpy's problem

Hi,

This is the right behavior for 'strncpy(s1,s2,n)' as it will copy exactly n bytes. The result will not be automatically null terminated if if the length of s2 is n or more.

After strncpy(str4,str3,4), you should set str[4] to null to properly terminate your string so that the printf statement will find the end of string where you want it to be.

Best regards,

Dan
Everybody knows at least one thing worth sharing -- mailto:dan.hetzel@wildcroft.com
Dan Hetzel
Honored Contributor

Re: strncpy's problem

Hi again,

Instead of strncpy(), you could use sprintf() to copy your data across strings.
This will allow formatting of the data.

Example:
#include
#include

main()
{
char a[20]="aaaaaaaaaaaaaaa";
char b[20]="bbbbbbbbbbbbbbb";

sprintf(b,"%4.4s",a);
printf("b is %s\n",b);
}

This prints 'b is aaaa' as it copies exactly 4 bytes.

See 'man sprintf' for information about all formatting capabilities.

Best regards,

Dan
Everybody knows at least one thing worth sharing -- mailto:dan.hetzel@wildcroft.com
Andreas Voss
Honored Contributor

Re: strncpy's problem

Hi,

you could make a procedure that adds the NULL termination ie:

void mystrncpy(dest, src, len)
char *dest;
char *src;
int len;
{
strncpy(dest, src, len);
dest[len] = 0;
}

Regards