【发布时间】:2011-11-07 23:43:15
【问题描述】:
我整天都在努力解决这个问题......
基本上,我有一个名为 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 编译示例。
【问题讨论】: