2017-03-06 51 views
-1

我是malloc的新手。我在哪裏會出現可怕的錯誤?無法在2D陣列中分配內存

#include <stdio.h> 
#include <stdio.h> 
#include <stdlib.h> 
typedef enum {RED_WINS, YELLOW_WINS, TIE, STILL_PLAYING} gamestate; 
typedef enum {EMPTY, RED_COIN, YELLOW_COIN} square; 

typedef struct { 
    int numRows, numCols; 
    int coinsInBoard; 
    gamestate state; 
    square** squares; 
} gameboard; 

gameboard* gameboard_create(int numRows, int numCols); 
void gameboard_print(const gameboard board); 
void gameboard_initialize(gameboard* board); 

這是我不知道我在做什麼比在任何地方。

// allocates space for the gameboard and its squares 
gameboard* gameboard_create(int numRows, int numCols) { 

        gameboard* result = malloc(sizeof(gameboard)); 
        result->squares= malloc(sizeof(square*)*numRows); 
        for(int i = 0; i<numRows; i++){ 
            result-> squares[i] = (square*)malloc(sizeof(square)*numCols); 
        } 
    for (int i =0; i< result->numRows; i++){ 
        for(int j= 0; j< result->numCols; j++){ 
             
            result->squares[i][j] = EMPTY; 
        } 
    } 
        return result; 
} 

// prints the coins currently in the board 
void gameboard_print(const gameboard board){ 
    for (int i = 0; i < board.numRows; i++) { 
        for (int j = 0; j < board.numCols; j++) { 
            printf("* "); 
        } 
        printf("\n"); 
        } 
} 

int main() { 
    printf("test\n"); 
    gameboard* result = gameboard_create(5, 5); 
    gameboard_print(*result); 
    return 0; 
} 

我想分配足夠的內存爲2D陣列,將播放連接4在任何大小的主板上。從「測試」

目前沒有什麼與衆不同的是印刷

+1

(1)究竟是什麼問題?具體說明(2)從'malloc'移除鑄件,因爲它們是多餘的(3)發佈[mcve] –

+0

這部分代碼是可以的。更明確你遇到什麼問題(併發布MCVE) –

+0

謝謝你們。試圖做mcve –

回答

0

的主要問題:

你忘了設定的result->numRowsresult->numCols值。因此,由於使用尚未初始化的變量而導致未定義的行爲。

是設置result->squares[i][j]EMPTY環之前的任何地方只需添加

result->numRows = numRows; 
result->numCols = numCols; 
gameboard_create


其它

  1. Don't cast the result of malloc (and family)。從

    刪除演員
    result-> squares[i] = (square*)malloc(sizeof(square)*numCols); 
    
  2. 養成你分配的所有內容free的習慣。但是,在您展示的小例子中,程序結束時內存會自動獲取freed,但對於free內存的使用,這是一個很好的做法。