我正在嘗試動態分配一個矩陣 N*N 并在其中放置亂數(0 和 h-1 之間)。我還必須創建一個解除分配它的函式。問題是我必須使用結構,而且我不太習慣它們。結構“game_t”在另一個檔案中定義并包含在內。
game_t * newgame( int n, int m, int t){
game_t x, *p;
int i,j;
p=&x;
x.t=t;
x.n=n; /* structure game has n,t,h,board as keys*/
x.h=h;
srand(time(NULL));
x.board=malloc(n*sizeof(int*)); /*Allocate*/
if (x.board==NULL) return NULL;
for (i=0;i<n;i ){
x.board[i]=malloc(n*sizeof(int));}
for (i=0;i<n;i ){ /*put random numbers*/
for (j=0;i<n;j ){
x.board[i][j]=rand()%h;}}
return p;
}
void destroy(game_t *p){
int i;
for (i=0;i<p->n;i ){
free(p->board[i]);}
free(p->board);
}
uj5u.com熱心網友回復:
p是一個指向區域變數,的指標x。一旦離開函式newgame,該變數就不再存在,p現在是一個懸空指標。您無權訪問它。
解決方案很簡單:回傳 a game_tfrom newgame,而不是 a newgame_t *,并且不要使用p:
game_t newgame(int n, int m, int t) {
game_t x;
int i, j;
x.t = t;
x.n = n; /* structure game has n,t,h,board as keys*/
x.h = h;
srand(time(NULL));
x.board = malloc(n * sizeof (int*)); /*Allocate*/
if (x.board == NULL) {
perror("newgame");
exit(1);
}
for (i = 0; i < n; i ) {
x.board[i] = malloc(n * sizeof(int));
if (x.board[i] == NULL) {
perror("newgame");
exit(1);
}
}
for (i = 0; i < n; i ) { /*put random numbers*/
for (j = 0; i < n; j ) {
x.board[i][j] = rand() % h;
}
}
return x;
}
請注意,這意味著NULL如果分配失敗,您將無法再回傳。我已經修改了代碼以退出,但可能需要不同的策略(盡管可能不是:分配失敗通常很難處理,退出 - 帶有錯誤訊息! - 是一個好的回應)。
uj5u.com熱心網友回復:
您回傳指向區域變數的指標x。一旦離開其作用域,區域變數就會消失。
game_t * newgame( int n, int m, int t){
game_t x, *p;
int i,j;
p=&x; // <<<< p points to the local variable x
x.t=t;
x.n=n;
x.h=h;
srand(time(NULL));
x.board=malloc(n*sizeof(int*));
if (x.board==NULL) return NULL;
for (i=0;i<n;i ){
x.board[i]=malloc(n*sizeof(int));}
for (i=0;i<n;i ){
for (j=0;i<n;j ){
x.board[i][j]=rand()%h;}}
return p;
}
你可能想要這個:
game_t * newgame( int n, int m, int t){
game_t *p = malloc(sizeof (*p)); // allocate memory for a new game_t
int i,j;
p->t=t;
p->n=n;
p->h=h;
srand(time(NULL));
p->board=malloc(n*sizeof(int*));
if (p->board==NULL) return NULL;
for (i=0;i<n;i ){
p->board[i]=malloc(n*sizeof(int));}
for (i=0;i<n;i ){
for (j=0;i<n;j ){
p->board[i][j]=rand()%h;}}
return p;
}
順便說一句:你應該使用有意義的變數名。例如p應該命名new等。
獎勵:在程式開始時srand(time(NULL))只呼叫一次。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/348678.html
