小编C l*_*ner的帖子

strncpy()和memcpy()有什么不同?

strncpy()memcpy()是一样的吗?

由于strncpy()只接受char*作为参数,因此将整数数组Icast为char*.

为什么它会得到不同的输出?

这是我的代码,

#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;
}
Run Code Online (Sandbox Code Playgroud)

事实证明

string2 =1234
string3 =1234
array2 ={ 1,0,0,0,0,} …
Run Code Online (Sandbox Code Playgroud)

c memcpy strncpy

3
推荐指数
1
解决办法
2757
查看次数

标签 统计

c ×1

memcpy ×1

strncpy ×1