打印 u_chars 数组
我有一个 u_chars 数组,我想使用 printf 打印它。我不知道数组的大小:
u_char *ip_p;
printf("%s", ip_p); // EXC_BAD_ACCESS D:<
我想打印它。我该怎么做?
I have an array of u_chars and I want to print it using printf. I don't know the size of the array:
u_char *ip_p;
printf("%s", ip_p); // EXC_BAD_ACCESS D:<
I want to print this. How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
那是不可能的。指针并不会神奇地包含有关所指向数据大小的信息。
如果没有约定(终止符字节或某处编码的长度),您将无法知道有多少数据是有效的,因此无法知道要打印多少数据。
That can't be done. A pointer doesn't magically contain information about the size of the data pointed to.
If there's no convention (a terminator byte, or a length encoded somewhere), you can't know how much data is valid, and thus how much to print.
如果您不知道大小,您如何期望
printf
知道呢?修复您的代码以将大小作为附加参数传递。然后您可以使用:但是看起来您的数据可能不是文本而是二进制。如果是这样,我质疑用 printf 打印它的价值......
If you don't know the size, how do you expect
printf
to know? Fix your code to pass the size as an additional argument. Then you can use:However it looks like your data might not be text but binary. If so, I question the value of printing it with
printf
...如果
ip_p
以 NUL 结尾,则您的代码可以正常工作。看看你的代码片段中的评论,我会说它没有终止......If
ip_p
is NUL terminated, your code works. Looking the comment in your code fragment I would say it isn't terminated...如果您不知道数据的大小,您如何希望使用它?该尺寸肯定在某处可用,否则它是如何放在那里的!?您必须知道大小或具有标记值(例如 nul 字符)。
如果它不是以 null 结尾,则“%s”是不适当的格式说明符。此外,如果 u_char 值并非都是可打印字符,则不应使用 %s 甚至 %c。您可以使用 %c 并将非打印字符替换为另一个字符。
If you don't know the size of the data how can you hope to use it? The size must have been available somewhere otherwise how did it get put there!? You must either know the size or have a sentinel value such as a nul character.
If it is not nul terminated, then "%s" is an inappropriate format specifier. Also if the u_char values are not all printable characters, you should not use %s or even %c. You might use %c and substitute non-printing characters with another.