我一整天都试着把头围住,
基本上,我有一个名为State的结构,名称为State,另一个名为StateMachine,名称,状态数组和状态总数:
#include <stdio.h> #include <stdlib.h> typedef struct State { const char * name; } State; typedef struct StateMachine { const char * name; int total_states; State ** states; } StateMachine; StateMachine * create_state_machine(const char* name) { StateMachine * temp; temp = malloc(sizeof(struct StateMachine)); if (temp == NULL) { exit(127); } temp->name = name; temp->total_states = 0; temp->states = malloc(sizeof(struct State)); return temp; } void destroy_state_machine(StateMachine* state_machine) { free(state_machine); } State * add_state(StateMachine* state_machine,const char* name) { State * temp; temp = malloc(sizeof(struct State)); if (temp == NULL) { exit(127); } temp->name = name; state_machine->states[state_machine->total_states]= temp; state_machine->total_states++; return temp; } int main(int argc,char **argv) { StateMachine * state_machine; State * init; State * foo; State * bar; state_machine = create_state_machine("My State Machine"); init = add_state(state_machine,"Init"); foo = add_state(state_machine,"Foo"); bar = add_state(state_machine,"Bar"); int i = 0; for(i; i< state_machine->total_states; i++) { printf("--> [%d] state: %s\n",i,state_machine->states[i]->name); } }
由于某些原因(阅读低C-fu /年的ruby / python / PHP)我无法表达这样一个事实,州是一个国家的数组.上述代码打印:
--> [0] state: ~ --> [1] state: Foo --> [2] state: Bar
第一个州增加了什么?
如果我在添加的第一个状态malloc状态数组(例如state_machine = malloc(sizeof(temp)));那么我得到第一个值,但不是第二个.
任何建议?
这是一个C问题.我使用gcc 4.2.1来编译示例.
解决方法
看起来你没有为机器分配空间超过第一个.
StateMachine * create_state_machine(const char* name) { StateMachine * temp; temp = malloc(sizeof(struct StateMachine)); if (temp == NULL) { exit(127); } temp->name = name; temp->total_states = 0; temp->states = malloc(sizeof(struct State)); // This bit here only allocates space for 1. return temp; }
在状态机结构中,你可能会把固定大小的状态数组放在一起.如果不行,你必须重新配置并移动整个集合,或者分配块并跟踪当前的长度,或者创建一个链表.
顺便提一句,init,foo和bar从不被使用.
编辑:我建议的内容如下所示:
#define MAX_STATES 128 // Pick something sensible. typedef struct StateMachine { const char * name; int total_states; State *states[MAX_STATES]; } StateMachine;