Asher Saban
Asher Saban

Reputation: 4793

return value of malloc

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

Upvotes: 2

Views: 1291

Answers (4)

Although the casting here in this case works for you. It is suggested that you make it a habit to cast things, before you try to assign them to a different type. It saves a lot of pain later. Also when incorporating this code into C++ it saves a lot of time.

Upvotes: 0

cyber_raj
cyber_raj

Reputation: 1857

In C, Casting for malloc is needed before ANSI C, as there was no void* type (perhaps as extension on some C compilers), but after ANSI C there is no need for casting at all, if you do that then you are suppressing some useful diagnostics by the compiler which is more harmful to your program. Never do casting on malloc() in C.

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

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++.

Upvotes: 5

nos
nos

Reputation: 229058

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.

Upvotes: 7

Related Questions