分配內存的結構我有一個struct稱爲國家:使用malloc
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分配給在狀態start_state期間創建的少量臨時空間,而不是分配給我分配的空間。 但是,當我嘗試註釋掉語句start_state = * start_state_pointer尊重指針並分配空間開始狀態。它給了我一個分段錯誤。
我剛剛開始在C.可以有人幫助我呢?
你想做什麼?這一行,'start_state_pointer =&(start_state);',拋出唯一指向分配內存的指針,永遠丟失它。 –
我試圖編譯你的代碼,並且得到了很多錯誤:http://codepad.org/RFQi7oHH/raw.txt – melpomene
我基本上試圖填充我用一個狀態創建的內存。即我想複製start_state並將其全部包含到新分配的內存中。 – user1452307