3

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?

4

2 回答 2

12
strncpy((char *)array2, (char*)array1 , sizeof(array1));

投射array1到 achar *不会做你想要的。该位置没有字符,只有整数(似乎是小端序)。

正在发生的事情是strncpy从整数数组复制字节,直到它达到 0 字节,这很快。另一方面memcpy,不关心 0 字节,只复制整个内容。

换句话说,strncpy在第一个整数“内部”找到一个 0 字节并停止复制;但是,它确实用零填充目标缓冲区,直到指定大小。

于 2013-09-03T17:01:22.793 回答
1

您可以用 实现(某种程度)strncpymemcpy但反过来就行不通,因为strncpy停在“字符串的末尾”,这对于不是 C 样式字符串的数据(例如其中有零字节)。

strncpy起来memcpy是这样的:

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;
}

(注意:上面的实现不适用于src字符串没有正确终止的情况——一个真实的strncpy可以解决这个问题——它可以在上面的代码中修复,但它变得相当复杂)。

于 2013-09-03T17:18:18.870 回答