我在使用指向结构成员的指针初始化数组时遇到问题。必须通过结构指针访问结构成员。原因是我们在运行时将指针初始化为内存映射地址位置。以下代码片段是该问题的示例;
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
long* lp;
}T;
typedef struct
{
long l;
}F;
F* f;
T t[] =
{
{ &f->l }
};
void init (void)
{
f = (F*) 0x08000100;
}
int main (void)
{
init();
return EXIT_SUCCESS;
}
编译器输出如下;
gcc -O0 -g3 -Wall -c -fmessage-length=0 -osrc\Test.o ..\src\Test.c ..\src\Test.c:18: error: initializer element is not constant ..\src\Test.c:18: error: (near initialization for `t[0].lp') ..\src\Test.c:18: error: initializer element is not constant ..\src\Test.c:18: error: (near initialization for `t[0]') Build error occurred, build is stopped
这里的问题是我们在运行时初始化指针,编译器不知道在哪里可以找到结构体成员。我们无法解决结构指针问题,因为我们不想为此使用链接描述文件。
有什么想法可以解决这个问题吗?
最佳答案
T t[] =
{
{ &f->l }
};
元素的地址(例如 &f->l)仅在运行时已知。
这样的值不能用于编译时初始化(这就是这里所做的)。
关于c - 指针数组的初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3966374/