int * [numRows]
is not a multiplication expression, it's a type - it's an array of pointer to int
. So sizeof (int * [numRows])
is the size (in bytes) of an array of int *
that's numRows
elements wide.
sizeof (int) * numRows
, OTOH, is a multiplication expression - you're multiplying the size of an int
by the number of rows. So, let's make some assumptions:
numRows == 10;
sizeof (int) == 4; // common on most platforms
sizeof (int *) == 8; // common on most 64-bit platforms
So, sizeof( int * [numRows])
gives us the size of a 10-element array of int *
, which would be 80. sizeof (int) * numRows
gives us the size of 10 int
objects, which is 40.
A cleaner and less error-prone way of writing that malloc
call would be
int **ans = malloc( sizeof *ans * numRows );
Since ans
has type int **
, the expression *ans
has type int *
, so sizeof *ans
is the same as sizeof (int *)
. So we're allocating enough space to hold numRows
instances of int *
.
Remember that sizeof
is an operator, not a function - the syntax is
sizeof ( type-name ) |
sizeof expression
It's a unary operator, which has higher precedence than a multiplication operator, so
sizeof *ans * numRows
will be parsed as
(sizeof *ans) * numRows
(int**)
is unnecessary. – Robert Harveysizeof(int)*numRows)
is a size ofnumRow
int
s.sizeof(int*[numRows])
is a size of array of pointers toint
. Totally different things – Eugene Sh.int *
notint
. Hence, the second one should besizeof(int *) * numRows
. – user3386109int **ans = malloc(sizeof(*ans) * numRows);
? – Craig Estey