Pra*_*rav 48
数组不会衰减为指针的三个例外如下:
例外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*) */
}
Run Code Online (Sandbox Code Playgroud)
例外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 */
}
Run Code Online (Sandbox Code Playgroud)
例外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) */
}
Run Code Online (Sandbox Code Playgroud)
假设声明
char foo[] = "This is a test";
char *bar = "This is a test";
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,字符串文字" This is a test
" 的类型是"15个元素的char数组".在大多数情况下,数组表达式被隐式地从类型"T的N元素数组"转换为"指向T的指针",并且表达式求值为数组的第一个元素的地址.在声明中bar
,这正是发生的事情.
foo
但是,在声明中,表达式用于初始化另一个数组的内容,因此不会转换为指针类型; 相反,字符串文字的内容被复制到foo
.
这是字符数组的文字字符串初始值设定项:
char arr[] = "literal string initializer";
Run Code Online (Sandbox Code Playgroud)
也可能是:
char* str = "literal string initializer";
Run Code Online (Sandbox Code Playgroud)
K&R2的定义:
字符串文字,也称为字符串常量,是由双引号括起来的字符序列,如"..."中所示.一个字符串有类型``字符数组''和存储类static(参见下面的参数A.3)并用给定的字符初始化.相同的字符串文字是否是不同的是实现定义的,并且尝试更改字符串文字的程序的行为是未定义的.
归档时间: |
|
查看次数: |
9740 次 |
最近记录: |