-1

这有点奇怪,但是在将数据从较小的数组复制到较大的数组时,我似乎在执行 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;
}
4

2 回答 2

2

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

于 2013-06-06T10:26:37.553 回答
1

也许你的问题不存在:

counter = counter |(data[3]<< 32);

发出警告:

left shift count >= width of type
于 2013-06-06T10:33:23.180 回答