gpt4 book ai didi

C 如何打印存储在 char 数组中的短整数?

转载 作者:太空宇宙 更新时间:2023-11-04 00:37:21 27 4
gpt4 key购买 nike

我有一个 char 数组并在其中存储了短整数:

char buf[50];
short int num = 12;

用 memcpy 填充:

memcpy(buf, &num, 50);

然后我尝试打印出来:

for(i=0; i <50;i++) {
printf("%hd|",buf[i]);
}

我认为 %hd 应该是打印出来的正确说明符。但我的输出如下:

12|0|0|0|0|0|0|0|12|0|0|0|0|0|0|0|12|0|0|0|0|0|0|0|12|0|0|0|0|0|0|0|12|0|0|0|0|0|0|0|12|0|0|0|0|0|0|0|12|0|

我的内容之间似乎有 7 字节空间(12)。但我想在每个字节中存储 "12"。应该可以在 char 数组中存储和缩短,我的意思是 1 个字节的最大表示是 256。我做错了什么? ...寻找一些好的建议 =)

在 linux 下开发。

最佳答案

你应该使用 memset 而不是 memcpy .


#include<stdio.h>
#include<string.h>
int main()
{
char buf[50];
int i;
short int num = 12;
memset(buf,num,50);

for(i=0; i <50;i++)
{
printf("%hd|",buf[i]);
}
return 0;
}

关于C 如何打印存储在 char 数组中的短整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26690719/

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