我一直在看
c pointer to array of structs
,并尝试将其应用于我的示例。
我得到了这个代码片段,它编译得很好:
#include <stdio.h>
enum test_e {
eONE,
eTWO,
eTHREE,
};
typedef enum test_e test_t;
#define NUMITEMS 12
extern test_t my_arr[NUMITEMS];
test_t (*my_arr_ptr)[NUMITEMS];
test_t my_arr[NUMITEMS] = { 0 };
int main()
{
my_arr_ptr = &my_arr;
printf("Hello World %p\n", my_arr_ptr);
return 0;
}
在上面的片段中,我们有一个
my_arr_ptr
变量,到的地址
my_arr
变量(使用“address of”运算符和
&
)。
然而,我想做的是
初始化
my_arr_ptr
变量的地址
my_arr
变量——我认为这是可能的,因为在这行之后
test_t my_arr[NUMITEMS] = { 0 };
编译器应该“知道”的地址和大小
my_arr
。
但是,如果我尝试这样做:
#include <stdio.h>
enum test_e {
eONE,
eTWO,
eTHREE,
};
typedef enum test_e test_t;
#define NUMITEMS 12
extern test_t my_arr[NUMITEMS];
test_t (*my_arr_ptr)[NUMITEMS];
test_t my_arr[NUMITEMS] = { 0 };
my_arr_ptr = &my_arr;
int main()
{
//my_arr_ptr = &my_arr;
printf("Hello World %p\n", my_arr_ptr);
return 0;
}
…失败的原因是:
Compilation failed due to following error(s).
main.c:25:1: warning: data definition has no type or storage class
25 | my_arr_ptr = &my_arr;
| ^~~~~~~~~~
main.c:25:1: warning: type defaults to âintâ in declaration of âmy_arr_ptrâ [-Wimplicit-int]
main.c:25:1: error: conflicting types for âmy_arr_ptrâ; have âintâ
main.c:21:10: note: previous declaration of âmy_arr_ptrâ with type âtest_t (*)[12]â {aka âenum test_e (*)[12]â}
21 | test_t (*my_arr_ptr)[NUMITEMS];
| ^~~~~~~~~~
main.c:25:14: warning: initialization of âintâ from âtest_t (*)[12]â {aka âenum test_e (*)[12]â} makes integer from pointer without a cast [-Wint-conversion]
25 | my_arr_ptr = &my_arr;
| ^
main.c:25:14: error: initializer element is not computable at load time
main.c: In function âmainâ:
main.c:30:26: warning: format â%pâ expects argument of type âvoid *â, but argument 2 has type âintâ [-Wformat=]
30 | printf("Hello World %p\n", my_arr_ptr);
| ~^ ~~~~~~~~~~
| | |
| | int
| void *
| %d
据我所见,出现了“警告:数据定义没有类型或存储类”:
因为你不能在函数外执行代码
(
Why am I getting this error: "data definition has no type or storage class"?
)
那么,获取“地址”是否被认为是C中的“代码”,所以我不能在函数外使用它?
如果是这样的话,为什么我可以在下面的代码段中使用“运算符外部函数的地址”,它也编译得很好?:
#include <stdio.h>
void func_one(void) {
printf("func_one\n");
}
void func_two(void) {
printf("func_two\n");
}
void* funcs_arr[2] = { &func_one, &func_two };
int main()
{
printf("Hello World %p\n", funcs_arr[0]);
return 0;
}