我有一个名为 State 的结构:
typedef struct State{
char alphabets[2][6];
struct State *PREV; /*this points to the previous state it came from*/
struct State *NEXT; /*this points to the next state in the linked list*/
int cost; /*Number of moves done to get to this position*/
int zero_index;/*this holds the index to the empty postion*/
} State;
这是我的 memAllocator() 方法:
memAllocator(){
struct State *p = (State*) malloc(sizeof(State));
if (p==NULL){
printf("Malloc for a new position failed");
exit(1);
}
return p;
这是我的主要方法。
main(){
State *start_state_pointer=memAllocator();
State start_state;
start_state.zero_index=15;
start_state.PREV = NULL;
start_state.alphabets[0][0]='C';
start_state.alphabets[0][1]='A';
start_state.alphabets[0][2]='N';
start_state.alphabets[0][3]='A';
start_state.alphabets[0][4]='M';
start_state.alphabets[0][5]='A';
start_state.alphabets[1][0]='P';
start_state.alphabets[1][1]='A';
start_state.alphabets[1][2]='N';
start_state.alphabets[1][3]='A';
start_state.alphabets[1][4]='L';
start_state.alphabets[1][5]='_';
start_state_pointer=&(start_state);
/*start_state=*start_state_pointer;*/
}
我认为语句 start_state_pointer=&(start_state); 只是将指针 start_state_pointer 分配给 State start_state 期间创建的少量临时空间,而不是分配给我分配的空间。但是,当我尝试使用注释掉的语句 start_state=*start_state_pointer 来尊重指针并分配空间以启动状态时。它给了我一个分段错误。
我刚从C开始。有人可以帮我吗?