以下代码完全有效,
int *ia = (int[]){1,3,5,7};
Run Code Online (Sandbox Code Playgroud)
但是当我编译下一行代码时,
char *p = (char[]) "abc";
Run Code Online (Sandbox Code Playgroud)
gcc说
test.c:87: error: cast specifies array type
Run Code Online (Sandbox Code Playgroud)
它们似乎以同样的方式铸造.为什么第二个得到一个错误的消息?
正如你们所说,"abc"是一个指针,它不能转换为指针.所以我的另一个问题是:为什么呢
char[] s = "abc";
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数组下标 …