strncpy() and memcpy() are different?

3.4k views Asked by At

strncpy() and memcpy() are the same?

Because of the fact that strncpy() only accepts char * as parameter, Icasts the integer arrays to char *.

Why it gets the different output?

Here is My code,

#define _CRT_SECURE_NO_WARNINGS 
#include <stdio.h>
#include <string.h>
#define SIZE 5


void print_array(int *array, char *name ,int len) {
    int i;
    printf("%s ={ ",name);
    for(i=0; i<len;i++)
        printf("%d," ,array[i]);
    printf("}\n");
}

int main(void){
    char string1[SIZE] = {'1','2','3','4','\0'};
    char string2[SIZE], string3[SIZE];
    int array1[SIZE] = {1,2,3,4,5};
    int array2[SIZE],array3[SIZE];

    strncpy(string2,string1,sizeof(string1));
    memcpy(string3, string1,sizeof(string1));
    printf("string2 =%s \n",string2);
    printf("string3 =%s \n",string3);

    strncpy((char *)array2, (char*)array1 , sizeof(array1));
    memcpy(array3,array1,sizeof(array1));
    print_array(array2,"array2",SIZE);
    print_array(array3,"array3",SIZE);

    return 0;
}

It turns out

string2 =1234
string3 =1234
array2 ={ 1,0,0,0,0,}
array3 ={ 1,2,3,4,5,}

But Why? It gives different answer?

2

There are 2 answers

4
Mats Petersson On

You can implement (sort of) strncpy with memcpy, but the other way around won't work, because strncpy stops at the "end of the string", which doesn't work at all well for data that isn't a C style string (e.g. has zero bytes in it).

To write strncpy with memcpy would be something like this:

char *strncpy(char *dest, const char *src, size_t maxlen)
{
   size_t len = strlen(src);
   memcpy(dest, src, min(len, maxlen));
   if (len < maxlen) memset(dest+len, 0, maxlen-len);
   return dest;
}

(Note: The above implementation doesn't work for the case where the src string is not terminated correctly - a real strncpy does cope with this - it could be fixed in the above code, but it gets quite complicated).

2
cnicutar On
strncpy((char *)array2, (char*)array1 , sizeof(array1));

Casting array1 to a char * doesn't do what you want. There are no characters at that location, there are only integers (little-endian it seems).

What is happening is that strncpy copies bytes from the integer array until it reaches a 0 byte, which is pretty soon. On the other hand memcpy doesn't care about 0 bytes and just copies the whole thing.

To put it another way, strncpy finds a 0 byte "inside" the first integer and stops copying; it does however fill the destination buffer with zeros up to the specified size.