如何打印带有嵌入式null的字符串

如何打印带有嵌入式null的字符串

本文介绍了如何打印带有嵌入式null的字符串,以便“(null)"替换为'\ 0'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用memcpy()组成的字符串,当扩展时,它看起来像这样:

I have a string I composed using memcpy() that (when expanded) looks like this:

char* str = "AAAA\x00\x00\x00...\x11\x11\x11\x11\x00\x00...";

我想打印字符串中的每个字符,如果字符为空,请打印出"(null)"来替代'\ 0'.

I would like to print every character in the string, and if the character is null, print out "(null)" as a substitute for '\0'.

如果我使用puts()或printf()之类的函数,它将以第一个null结尾并打印出来

If I use a function like puts() or printf() it will just end at the first null and print out

AAAA

那么如何在不将其解释为字符串末尾的情况下打印出实际的单词(null)"呢?

So how can I get it to print out the actual word "(null)" without it interpreting it as the end of the string?

推荐答案

您必须自己进行映射.如果您愿意,那就是.在C中,字符串以null终止.因此,如果您使用格式化的输出函数(例如printfputs)并要求它打印字符串(通过格式说明符%s),它将在它遇到第一个null时立即停止打印str. . C中没有null词.如果您确切地知道str中有多少个字符,则最好遍历它们并单独打印出字符,用所选的助记符代替0.

You have to do that mapping yourself. If you want to, that is. In C, strings are null-terminated. So, if you use a formatted output function such as printf or puts and ask it to print a string (via the format specifier %s) it'd stop printing str as soon as it hits the first null. There is no null word in C. If you know exactly how many characters you have in str you might as well loop over them and print the characters out individually, substituting the 0 by your chosen mnemonic.

草案说出7.21.6.1/8:

The draft says 7.21.6.1/8:

但是,以下内容:

$ cat null.c
#include <stdio.h>
int main() {
 printf("%p\n", (void *)0);
}

产生:

00000000

在gcc 4.6和clang 3.2上.

on both gcc 4.6 and clang 3.2.

但是,在更深入的研究中:

However, on digging deeper:

$ cat null.c
#include <stdio.h>
int main() {
 printf("%s\n", (void *)0);
}

确实可以产生所需的输出:

does indeed produce the desired output:

(null)

在gcc和clang上.

on both gcc and clang.

请注意,该标准并不强制执行以下操作:

Note that the standard does not mandate this:

依靠这种行为可能会导致意外!

Relying on this behavior may lead to surprises!

这篇关于如何打印带有嵌入式null的字符串,以便“(null)"替换为'\ 0'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 09:22