typedef struct trans * Trans;
typedef struct state{
int f;
char label[20];
trans * TrasitionsArray[10];
}state;
struct trans{
state * from;
state * to;
char label;
};
void main(){
state StatesArray[100];
}
我如何为(state---trasition---to---label)赋值
我尝试过但失败了:
strcpy(StatesArray[i].TrasitionsArray[j]->to->label,"blahblah");
最佳答案
state StatesArray[100];
仅为状态的结构成员分配内存。它只会为 TrasitionsArray
分配 10 * 4 字节(32bit m/c 中的指针大小)来保存十个 Transition
结构变量。但是没有为 transition
结构变量的成员分配内存。对于 from
和 to
结构变量也类似。
使用下面的示例代码来分配内部指针变量。
int i, j;
struct state states[100];
for (i = 0; i < 100; i++)
{
for (j = 0; j < 10; j++)
{
StatesArray[i].TrasitionsArray[j] = (struct trans*)malloc(sizeof(struct trans));
StatesArray[i].TrasitionsArray[j]->from = (struct state *)malloc(sizeof(struct state));
StatesArray[i].TrasitionsArray[j]->to = (struct state *)malloc(sizeof(struct state));
}
}
注意:请注意 NULL
检查 malloc
的返回值
关于c - 如何遍历这个由多个结构体、数组和指针组成的 C 数据结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11129071/