字符数组应如何用作字符串? [英] How should character arrays be used as strings?

查看:146
本文介绍了字符数组应如何用作字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道C语言中的字符串只是字符数组.因此,我尝试了以下代码,但给出了奇怪的结果,例如垃圾输出或程序崩溃:

I understand that strings in C are just character arrays. So I tried the following code, but it gives strange results, such as garbage output or program crashes:

#include <stdio.h>

int main (void)
{
  char str [5] = "hello";
  puts(str);
}

为什么这行不通?

它可以用gcc -std=c17 -pedantic-errors -Wall -Wextra干净地编译.

It compiles cleanly with gcc -std=c17 -pedantic-errors -Wall -Wextra.

注意::该帖子旨在作为规范的常见问题解答,用于因声明字符串时未能为NUL终止符分配空间而引起的问题.

Note: This post is meant to be used as a canonical FAQ for problems stemming from a failure to allocate room for a NUL terminator when declaring a string.

推荐答案

C字符串是一个以 null终止符结尾的字符数组.

A C string is a character array that ends with a null terminator.

所有字符都有符号表值.空终止符是符号值0(零).它用于标记字符串的结尾.这是必需的,因为字符串的大小不会存储在任何地方.

All characters have a symbol table value. The null terminator is the symbol value 0 (zero). It is used to mark the end of a string. This is necessary since the size of the string isn't stored anywhere.

因此,每次为字符串分配空间时,都必须为空终止符包含足够的空间.您的示例不执行此操作,它仅为"hello"的5个字符分配空间.正确的代码应为:

Therefore, every time you allocate room for a string, you must include sufficient space for the null terminator character. Your example does not do this, it only allocates room for the 5 characters of "hello". Correct code should be:

char str[6] = "hello";

或者等效地,您可以编写5个字符加1个空终止符的自文档代码:

Or equivalently, you can write self-documenting code for 5 characters plus 1 null terminator:

char str[5+1] = "hello";

在运行时为字符串动态分配内存时,还需要为null终止符分配空间:

When allocating memory for a string dynamically in run-time, you also need to allocate room for the null terminator:

char input[n] = ... ;
...
char* str = malloc(strlen(input) + 1);

如果您没有在字符串的末尾附加一个空终止符,那么期望该字符串的库函数将无法正常工作,并且您将得到未定义行为"的错误,例如垃圾输出或程序崩溃.

If you don't append a null terminator at the end of a string, then library functions expecting a string won't work properly and you will get "undefined behavior" bugs such as garbage output or program crashes.

在C中写空终止符的最常见方法是使用所谓的八进制转义序列",如下所示:'\0'.这相当于写0的100%,但是\用作自文档代码,指出零明确表示是空终止符. if(str[i] == '\0')之类的代码将检查特定字符是否为空终止符.

The most common way to write a null terminator character in C is by using a so-called "octal escape sequence", looking like this: '\0'. This is 100% equivalent to writing 0, but the \ serves as self-documenting code to state that the zero is explicitly meant to be a null terminator. Code such as if(str[i] == '\0') will check if the specific character is the null terminator.

请注意,术语空终止符与空指针或NULL宏无关!这可能会造成混淆-名称非常相似,但含义却截然不同.这就是为什么将空终止符有时称为带有一个L的NUL,不要与NULL或空指针混淆的原因.有关更多详细信息,请参见此SO问题的答案.

Please note that the term null terminator has nothing to do with null pointers or the NULL macro! This can be confusing - very similar names but very different meanings. This is why the null terminator is sometimes referred to as NUL with one L, not to be confused with NULL or null pointers. See answers to this SO question for further details.

您代码中的"hello"被称为字符串文字.这将被视为只读字符串. ""语法意味着编译器将自动在字符串文字的末尾附加一个空终止符.因此,如果您打印出sizeof("hello"),您将得到6,而不是5,因为得到的数组大小包括空终止符.

The "hello" in your code is called a string literal. This is to be regarded as a read-only string. The "" syntax means that the compiler will append a null terminator in the end of the string literal automatically. So if you print out sizeof("hello") you will get 6, not 5, because you get the size of the array including a null terminator.

它可以用gcc干净地编译

It compiles cleanly with gcc

的确,甚至没有警告.这是由于C语言中的一个细微的细节/缺陷,它允许使用字符串文字初始化字符数组,该字符串文字包含的字符与数组中的空间一样多,然后静默丢弃空终止符(C17 6.7.9/15).出于历史原因,该语言的行为故意是这样的,请参阅字符串初始化的gcc诊断不一致有关详细信息.另外请注意,C ++在这里有所不同,并且不允许使用此技巧/缺陷.

Indeed, not even a warning. This is because of a subtle detail/flaw in the C language that allows character arrays to be initialized with a string literal that contains exactly as many characters as there is room in the array and then silently discard the null terminator (C17 6.7.9/15). The language is purposely behaving like this for historical reasons, see Inconsistent gcc diagnostic for string initialization for details. Also note that C++ is different here and does not allow this trick/flaw to be used.

这篇关于字符数组应如何用作字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆