malloc的返回值

Ash*_*ban 2 c

我有以下代码部分:

typedef struct Board* BoardP;

typedef struct Board {
    int _rows;
    int _cols;
    char *_board;

} Board;

char* static allocateBoard(BoardP boardP, int row, int col) {

    boardP->_rows = row;
    boardP->_cols = col;
    boardP->_board = malloc(row * col * sizeof(char));

    return boardP->_board;
}
Run Code Online (Sandbox Code Playgroud)

我似乎无法弄清楚为什么它给出了错误预期的标识符或'(''''''之前它给出了错误,我将返回类型更改为char*.当它为void时没有给出错误.

还有一个问题:我被告知在使用malloc时需要强制转换,但是,这似乎在没有强制转换的情况下正常工作.在这种情况下是否需要?

谢谢

nos*_*nos 6

将您的功能更改为

static char* allocateBoard(BoardP boardP, int row, int col):
Run Code Online (Sandbox Code Playgroud)

malloc的返回值是void*,在C中(与C++不同),void*可以隐式转换为任何其他指针类型 - 除了函数指针.所以你不需要演员.


Oli*_*rth 5

你的函数原型需要是:

static char* allocateBoard(BoardP boardP, int row, int col)
Run Code Online (Sandbox Code Playgroud)

malloc()C中不需要演员阵容; 但是,它是在C++中.