memcpy() 将整数值复制到字符缓冲区
我正在尝试将 int 的内存值复制到 char 缓冲区中。代码如下所示,
#define CPYINT(a, b) memcpy(a, &b, 4)
............
char str1[4];
int i = 1;
CPYINT(str1, i);
printf("%s",s);
...........
当我打印 str1 时,它是空白的。请澄清。
I am trying to copy the memory value of int into the char buffer. The code looks like below,
#define CPYINT(a, b) memcpy(a, &b, 4)
............
char str1[4];
int i = 1;
CPYINT(str1, i);
printf("%s",s);
...........
When I print str1 it’s blank. Please clarify.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您正在将整数的字节表示形式复制到 char 数组中。然后,您要求
printf
将此数组解释为空终止字符串:str1[0]
为零,您实际上是在打印一个空字符串(我正在跳过 字节序 在此讨论)。你期待什么?显然,如果您想打印整数
i
的文本表示形式,则应该使用printf("%d", i)
。You are copying the byte representation of an integer into a char array. You then ask
printf
to interpret this array as a null terminating string :str1[0]
being zero, you are essentially printing an empty string (I'm skipping the endianness talk here).What did you expect ? Obviously, if you wanted to print a textual representation of the integer
i
, you should useprintf("%d", i)
.尝试
一下。
整数 1 的二进制表示形式可能包含前导 NUL,因此当前的 printf 语句比您想要的更早终止。
try
instead.
The binary representation of the integer 1, probably contains leading NULs, and so your current printf statement terminates earlier than you want.
你来这里的目的是什么?现在,您将任意字节值放入 char 数组中,但随后将它们解释为字符串,因为它碰巧第一个字节可能是零(空),因此您什么也不打印,但很可能许多字符将是无法打印,因此 printf 是用来检查副本是否有效的错误工具。
因此,要么:循环遍历数组并打印每个字节的数值,%0xd 可能对此有用,或者如果您的意图实际上是创建 int 的字符串表示形式,那么您将需要更大的缓冲区和空间空终止符。
What is your intention here? Right now you are putting arbitrary byte values into the char array, but then interpreting them as a string, as it happens the first byte is probably a zero (null) and hence your print nothing, but in all probability many of the characters will be unprintable, so printf is the wrong tool to use to check if the copy worked.
So, either: loop through the array and print the numeric value of each byte, %0xd might be useful for that or if your intention is actually to create a string representation of the int then you'll need a larger buffer, and space for a null terminator.
也许你需要将 intger 转换为 char* 这样你就可以使用 itoa 函数
链接文本
Maybe you need convert intger to char* in that way tou can use itoa function
link text