以下声明之间有什么区别:
int* arr1[8];
int (*arr2)[8];
int *(arr3[8]);
Run Code Online (Sandbox Code Playgroud)
理解更复杂的声明的一般规则是什么?
考虑:
char amessage[] = "now is the time";
char *pmessage = "now is the time";
Run Code Online (Sandbox Code Playgroud)
我从C编程语言第2版中读到,上述两个陈述没有做同样的事情.
我一直认为数组是一种操作指针来存储一些数据的便捷方式,但显然情况并非如此...... C中数组和指针之间的"非平凡"差异是什么?
我以为我真的理解这一点,并重新阅读标准(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数组下标 …