Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return value of malloc

Tags:

c

I have the following code parts:

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;
}

i can't seem to figure out why it gives the error expected identifier or ‘(’ before ‘static’ it gives the error after i changed return type to be char*. when it was void no error was given.

and one more question: i was taught that cast is needed when using malloc, however, this seems to be working ok without a cast. is it needed in this case?

thanks

like image 750
Asher Saban Avatar asked Sep 01 '26 11:09

Asher Saban


2 Answers

Change your function to

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

The return value of malloc is a void*, and in C (unlike C++), a void* is implicittly convertible to any other pointer type - except function pointers. so you don't need a cast.

like image 74
nos Avatar answered Sep 04 '26 07:09

nos


Your function prototype needs to be:

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

No cast is needed on malloc() in C; however, it is in C++.

like image 21
Oliver Charlesworth Avatar answered Sep 04 '26 07:09

Oliver Charlesworth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!