gpt4 book ai didi

可以语句 char str[] ="abcdef";和 char *str ="abcdef";用于解释C中的字符数组和字符串文字?

转载 作者:行者123 更新时间:2023-11-30 18:32:39 24 4
gpt4 key购买 nike

Possible Duplicate:
What is the difference between char s[] and char *s in C?

可以声明吗

char str[]="abcdef"; 

char *str="abcdef"; 

用来解释C中的字符数组和字符串文字?字符数组和字符串文字之间有什么关系?除了存储字符串文字之外,char 数组的实际用途是什么?

最佳答案

字符串文字是不可修改的 char 数组。

C99 6.4.5 p2:

A character string literal is a sequence of zero or more multibyte characters enclosed in double-quotes, as in "xyz".

然后,在 C99 6.4.5 p5 中:

In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals. The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence;...

我手上的 C11 草案也有类似的措辞。我相信它的措辞是“具有类型 char”,正是为了允许将字符串文字分配给 char *。然而,该标准在 C99 6.4.5 p6 中继续说道:

If the program attempts to modify such an array, the behavior is undefined.

可分配,但不可修改。

字符串文字可以用作 char 数组的初始值设定项。从 C99 6.7.8 p14 开始:

An array of character type may be initialized by a character string literal, optionally enclosed in braces. Successive characters of the character string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

关于可以语句 char str[] ="abcdef";和 char *str ="abcdef";用于解释C中的字符数组和字符串文字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11734252/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com