如何在C中打印结构体中的三个字节
我有以下 C 代码:
person->title
标题是一个三字节字符数组。我想做的就是打印这三个字节。我无法将字符串格式化程序与 printf 一起使用,因为没有空字节。
如何打印出来而不必复制它或向其中添加空字节?
提前致谢!
更新
事实证明它不是一个数组,只是三个相邻的字节。如果我尝试使用建议的代码进行编译:
person->title[0]
它会失败并出现错误:
test.c:46: error: subscripted value is neither array nor pointer.
I have the following C code:
person->title
The title is a three byte char array. All I want to do is print those three bytes. I can't use the string formatter with printf because there is no null byte.
How can I print this out without having to copy it or add a null byte to it?
Thanks in advance!
UPDATE
Turns out it's not an array, just three adjacent bytes. If I try to compile with the code suggested:
person->title[0]
It fails with the error:
test.c:46: error: subscripted value is neither array nor pointer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
请尝试这个....
编辑
基于结构中的20个字段,它更简单,在结构的情况下会发生连续的内存分配,
例如:
Please try this....
EDIT
Based on 20 fields in the struct it`s much more simple mate, contiguous memory allocation takes place in case of struct
eg:
您可以使用类似的内容:
如果您确定三个字节已填充。如果它可能短于三个字节,请尝试以下操作:
You could use something like:
if you are sure the three bytes are filled. If it could be shorter than three bytes, try something like:
对于结构 - 您可以利用内存将被分配为连续字节的事实。您还可以使用 fwrite() 来精确控制写入的字节数(如果您希望将其打印到终端,则使用“stdout”作为文件指针)。
例如
将输出:
For structs - you could exploit the fact that the memory will be allocated as contiguous bytes. You could also use fwrite() to control exactly how many bytes are written (using "stdout" as file pointer if you want it printed to the terminal).
e.g.
Will output: