打印 u_chars 数组

发布于 2024-10-06 17:13:46 字数 155 浏览 0 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

对不⑦ 2024-10-13 17:13:47

那是不可能的。指针并不会神奇地包含有关所指向数据大小的信息。

如果没有约定(终止符字节或某处编码的长度),您将无法知道有多少数据是有效的,因此无法知道要打印多少数据。

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.

淡淡的优雅 2024-10-13 17:13:47

如果您不知道大小,您如何期望 printf 知道呢?修复您的代码以将大小作为附加参数传递。然后您可以使用:

printf("%.*s", size, buf);

但是看起来您的数据可能不是文本而是二进制。如果是这样,我质疑用 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:

printf("%.*s", size, buf);

However it looks like your data might not be text but binary. If so, I question the value of printing it with printf...

紙鸢 2024-10-13 17:13:47

如果 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...

树深时见影 2024-10-13 17:13:47

如果您不知道数据的大小,您如何希望使用它?该尺寸肯定在某处可用,否则它是如何放在那里的!?您必须知道大小或具有标记值(例如 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文