gpt4 book ai didi

c - 使用 strncpy 从较小的数据数组复制到较大的数据数组时丢失数据

转载 作者:行者123 更新时间:2023-11-30 18:42:23 25 4
gpt4 key购买 nike

这有点奇怪,但我在将数据从较小的数组复制到较大的数组时执行 strncpy 时似乎丢失了数据。我很不明白为什么会发生这种情况。请帮忙!这是代码(从较大的代码中截取的)

#include <stdlib.h>     
#include <stdio.h>
#include <string.h>

#define SIZE_UNSIGNED_LONG_LONG 8
#define DATALEN 2048

int main(int argc, char *argv[])
{

printf("size of unsigned long long is %d \n", sizeof(unsigned long long));

//unsigned long long to unsigned char
unsigned long long a = 3;
unsigned char cval[8];
cval[7] = (a & 0xFF);
cval[6] = ((a >> 8) & 0xFF);
cval[5] = ((a >> 16) & 0xFF);
cval[4] = ((a >> 24) & 0xFF);
cval[3] = ((a >> 32) & 0xFF);
cval[2] = ((a >> 40) & 0xFF);
cval[1] = ((a >> 48) & 0xFF);
cval[0] = ((a >> 56) & 0xFF);

unsigned char data[2048];
strncpy((char *)data,(char *)cval, SIZE_UNSIGNED_LONG_LONG);//destination buffer

//unsigned char to unsigned long long
unsigned long long counter = 0;
counter = counter |(data[7]);
counter = counter |(data[6]<< 8);
counter = counter |(data[5]<< 16);
counter = counter |(data[4]<< 24);
counter = counter |(data[3]<< 32);
counter = counter |(data[2]<< 40);
counter = counter |(data[1]<< 48);
counter = counter |(data[0]<< 56);
printf("Trial1: counter is = %llu\n", counter);
counter = 0;
counter = counter |(data[0]);
counter = counter |(data[1]<< 8);
counter = counter |(data[2]<< 16);
counter = counter |(data[3]<< 24);
counter = counter |(data[4]<< 32);
counter = counter |(data[5]<< 40);
counter = counter |(data[6]<< 48);
counter = counter |(data[7]<< 56);
printf("Trial2: counter is = %llu\n", counter);

return 0;
}

最佳答案

您应该使用memcpy(),而不是使用strncpy()strncpy() 如果找到空('\0')字符,则用零填充剩余字节。

关于c - 使用 strncpy 从较小的数据数组复制到较大的数据数组时丢失数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16959598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com