【发布时间】:2015-08-03 14:39:57
【问题描述】:
uint32_t after = 0xe1ca95ee;
char new_buf[4];
memcpy(new_buf, &after, 4);
printf("%x\n", *new_buf); // I want to print the content of new_buf
我想将after的内容复制到new_buf。但结果令人困惑。 printf 给了我ffffffee。它看起来像一个地址。我已经取消引用new_buf。
根据 cmets,我不能使用 memcpy 或 strncpy 来执行此任务。但为什么? memcpy 和 strncpy 仅设计用于处理 char *?但是after的内容在内存中。
PS:我知道我应该使用sprintf 或snprintf。如果你能解释为什么memcpy 和strncpy 不适合这种情况,我很感激。
【问题讨论】:
-
你确定要这样做
memcpy()? -
您希望打印什么?您可以尝试完成几件不同的事情,但我不知道是哪件。
-
直到代码需要“将整数复制到字符缓冲区”的更大问题之前,答案仍然很短。将
uint32_t after复制到uint8_t new_buf8[4];是有道理的,但复制到char []暗示了一个更大的编码目标的开始,这是有问题的。
标签: c