在C中的变量之间复制

use*_*678 1 c variables copy

我想将unsigned int值复制到char [2]变量.我认为复制是直截了当的,因为它们都具有相同的大小(16位).这是我的代码:

#include <stdlib.h>
#include <stdio.h>
int main()
{
    unsigned short a = 63488; //16 bit value which is 1111100000000000;
    unsigned char* b = malloc(2); 
    *b = a;
    printf("%d\n",b[0]); // I expect the lower part here which is 0
    printf("%d\n",b[1]); // I expect the higher part here which is 11111000
    return 0;
} 
Run Code Online (Sandbox Code Playgroud)

但我的结果显示零值.我是否必须单独复制每个部分?没有其他更简单的方法吗?

谢谢

Jon*_*art 5

如果你只是想解释short是一个char数组,你甚至不需要复制.刚演员:

#include <stdio.h>
int main()
{
    size_t i;
    unsigned short a = 63488;
    unsigned char* b = (unsigned char*)&a;    // Cast the address of a to
                                              // a pointer-to-unsgigned-char

    printf("Input value: %d (0x%X)\n", a, a);

    printf("Each byte:\n");
    for (i = 0; i < sizeof(a); i++)
        printf("b[%d] = %d (0x%X)\n", i, b[i], b[i]);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

$ gcc -Wall -Werror so1.c && ./a.out
Input value: 63488 (0xF800)
Each byte:
b[0] = 0 (0x0)
b[1] = 248 (0xF8)
Run Code Online (Sandbox Code Playgroud)

请注意,我在我的x86 PC上运行它,这是一个小端机器,这就是为什么第一个字节是输入的低字节.

另请注意,我的代码也从不对大小做出假设short.