字符数组的文字字符串初始值设定项 [英] Literal string initializer for a character array
问题描述
对于数组衰减为指针的情况,规则如下:
In the following rules for the case when array decays to pointer:
出现在表达式中的array-of-T类型的左值[见问题2.5]衰减(三个例外)为指向其第一个元素的指针;结果指针的类型是指向T的指针.
An lvalue [see question 2.5] of type array-of-T which appears in an expression decays (with three exceptions) into a pointer to its first element; the type of the resultant pointer is pointer-to-T.
(例外情况是数组是 sizeof 或 & 运算符的操作数,或者是字符数组的文字字符串初始值设定项.)
(The exceptions are when the array is the operand of a sizeof or & operator, or is a literal string initializer for a character array.)
如何理解数组是字符数组的文字字符串初始化器"的情况?请举个例子.
How to understand the case when the array is "literal string initializer for a character array"? Some example please.
谢谢!
推荐答案
数组不会衰减为指针的三个例外如下:
The three exceptions where an array does not decay into a pointer are the following:
异常 1. — 当数组是 sizeof
的操作数时.
Exception 1. — When the array is the operand of sizeof
.
int main()
{
int a[10];
printf("%zu", sizeof(a)); /* prints 10 * sizeof(int) */
int* p = a;
printf("%zu", sizeof(p)); /* prints sizeof(int*) */
}
异常 2. — 当数组是 &
运算符的操作数时.
Exception 2. — When the array is the operand of the &
operator.
int main()
{
int a[10];
printf("%p", (void*)(&a)); /* prints the array's address */
int* p = a;
printf("%p", (void*)(&p)); /*prints the pointer's address */
}
异常 3. — 当数组用文字字符串初始化时.
Exception 3. — When the array is initialized with a literal string.
int main()
{
char a[] = "Hello world"; /* the literal string is copied into a local array which is destroyed after that array goes out of scope */
char* p = "Hello world"; /* the literal string is copied in the read-only section of memory (any attempt to modify it is an undefined behavior) */
}
这篇关于字符数组的文字字符串初始值设定项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!