在数组衰减为指针的情况下有以下规则:
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.
(The exceptions are when the array is the operand of a sizeof or & operator, or is a literal string initializer for a character array.)
如何理解数组是“字符数组的文字字符串初始值设定项”的情况?请举个例子。
谢谢!
最佳答案
数组不会衰减为指针的三个异常(exception)情况如下:
异常(exception) 1. — 当数组是 sizeof
的操作数时。
int main()
{
int a[10];
printf("%zu", sizeof(a)); /* prints 10 * sizeof(int) */
int* p = a;
printf("%zu", sizeof(p)); /* prints sizeof(int*) */
}
异常(exception) 2. — 当数组是 &
运算符的操作数时。
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. — 当数组用文字字符串初始化时。
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) */
}
关于c - 字符数组的文字字符串初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2036096/