c - 字符数组的文字字符串初始值设定项

标签 c string pointers arrays c99

在数组衰减为指针的情况下有以下规则:

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/

相关文章:

c - 何时将指针参数传递给函数

Java String.matches ("regex")

c - 在 C 中使用 atoi() 解析具有二进制值的字符数组

python - 使用正则表达式在python中的两个字符串之间提取字符串

c++ - 从动态数组中删除一个动态对象

C - ULL 前缀,十六进制

c - 内核驱动程序: How get correct content of each variable in a struct?

c++ - 作弊 Linux : executables and dependent libraries via LD_PRELOAD

c++ - C++中指向字符数组的指针

c - 从 C 中的文本文件中读取