文字字符串初始化一个字符数组 [英] Literal string initializer for a character array

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

问题描述

在该情况下,下面的规则时,阵列衰减到指针:

In the following rules for the case when array decays to pointer:

这是左值[参见问题2.5]型数组的-T出现在一个前pression衰变(有三个例外)到一个指向它的第一要素;所得指针的类型是指针到-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

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屋!

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