我一整天都在努力理解这个问题...
基本上,我有一个名为“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),我无法表达 states 是 State(s)数组的事实。以上代码输出:
出现问题了,我不太懂如何将 states 表示为 State(s)数组。上述代码输出:
--> [0] state: ~
--> [1] state: Foo
--> [2] state: Bar
第一个添加的状态发生了什么?
如果我在第一个状态添加时使用malloc分配状态数组(例如state_machine = malloc(sizeof(temp));),那么我可以得到第一个值但无法得到第二个值。
有什么建议吗?
这是一个关于C语言的问题。我正在使用gcc 4.2.1编译示例代码。
StateMachine
中放置一个State *
数组应该可以工作,只要确保不超出它的范围。 - nmichaels