我对以下内容感到有些惊讶.
例1:
char s[100] = "abcd"; // declare and initialize - WORKS
Run Code Online (Sandbox Code Playgroud)
例2:
char s[100]; // declare
s = "hello"; // initalize - DOESN'T WORK ('lvalue required' error)
Run Code Online (Sandbox Code Playgroud)
我想知道为什么第二种方法不起作用.它应该是自然的(它适用于其他数据类型)?有人能解释一下这背后的逻辑吗?
我以为我真的理解这一点,并重新阅读标准(ISO 9899:1990)只是证实了我明显错误的理解,所以现在我问这里.
以下程序崩溃:
#include <stdio.h>
#include <stddef.h>
typedef struct {
int array[3];
} type1_t;
typedef struct {
int *ptr;
} type2_t;
type1_t my_test = { {1, 2, 3} };
int main(int argc, char *argv[])
{
(void)argc;
(void)argv;
type1_t *type1_p = &my_test;
type2_t *type2_p = (type2_t *) &my_test;
printf("offsetof(type1_t, array) = %lu\n", offsetof(type1_t, array)); // 0
printf("my_test.array[0] = %d\n", my_test.array[0]);
printf("type1_p->array[0] = %d\n", type1_p->array[0]);
printf("type2_p->ptr[0] = %d\n", type2_p->ptr[0]); // this line crashes
return 0;
}
Run Code Online (Sandbox Code Playgroud)
比较表达式my_test.array[0]并type2_p->ptr[0]根据我对标准的解释:
6.3.2.1数组下标 …
语境:
我在C中打开和关闭编程大约2年,然后发现它a[i]只是语法糖,*(a + i)因此相当于*(i + a)和i[a].我的现实被颠倒了,很多都是"AHA!" 在接下来的几天学习和阅读之后出现了启示时刻("那就是为什么数组总是通过引用传递!"等).从那时起,我已经内化了指针/数组的等价并将其保持在我心中,所以想象一下,当我偶然发现这个名为"数组衰变"的东西时,这是多么可怕的震撼.这是典型的例子:
码:
#include <stdio.h>
int Length(int*);
int main () {
int arr[100];
printf("Length of array: %d\n",(int)(sizeof(arr)/sizeof(arr[0])));
printf("Length of array: %d\n",Length(arr));
return 0;
}
int Length(int arr[]) {
return sizeof(arr)/sizeof(arr[0]);
}
Run Code Online (Sandbox Code Playgroud)
结果:
Length of array: 100
Length of array: 2
Run Code Online (Sandbox Code Playgroud)
题:
事实证明,C毕竟对数组有一些认识!在声明数组的main中,程序能够正确地报告它的大小.现在我想知道有多少数组语法只是指针操作的语法糖(之前我曾假设:所有这些).C实际上确实有数组,它们的局限性是什么?这个例子表明只要你在同一个函数中就可以获得它们的长度,你可以做些什么呢?在这种腐烂的事情发生之前你能走多远?