darylnak darylnak -4 years ago 110
C Question

How to malloc() With Custom Types?

In a header file -- gameboard.h -- I have a struct named gameboard. In this struct I declare

square **squares
, where squares is the following:
typedef enum {EMPTY, RED_COIN, YELLOW_COIN} square;


In gameboard.c, I have a function that allocates memory for a 2D array. In this function I declare
gameboard* result
.

Question: When creating the initial array, i.e. the part of a 2D that will store an array, why can't I do this:

result->squares = malloc(numRows * sizeof(result->square*));


More specifically, why is square an invalid type?

Answer Source

You cannot "do this" because your result->square subexpression is invalid. result->squares would be valid. Plain square would be valid too. But result->square makes no sense at all. In C -> is a member access operator. And your struct type does not have a member named square.

  • A typical/idiomatic C code for malloc-ing an array of objects would look as follows

    some_pointer = malloc(n_elements * sizeof *some_pointer);
    

    Applying this to your case we get

    result->squares = malloc(numRows * sizeof *result->squares);
    
  • If your result->squares has type square **, then the proper size can also be expressed in terms of sizeof(array_element_type) as

    result->squares = malloc(numRows * sizeof(squares *));
    

    But the former (type-agnostic) variant is arguably better than this latter version, specifically for being type-agnostic. See also: Why is it safer to use sizeof(*pointer) in malloc

How you managed to arrive at sizeof(result->square*) is completely unclear to me. Your variant looks like a bizarre hybrid of the two, written in incorrect and meaningless way.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download