Search code examples
cmultiplicationassociativity

Is there any difference between these two?


I donno if this is possible or not but am confused. Are they both same? I know that in the first case we are allocating memory dynamically for 20 elements of type int.

int *p;
p=(int *) malloc(20*sizeof(int));

and

p=(int *) malloc(sizeof(int)*20);

Solution

  • Recall that sizeof operator returns type: size_t.

    In the case of int * size_t (20*sizeof(int)) versus size_t * int (sizeof(int) * 20): the product is the same as the narrower type is widened to the other first and multiplication in C is commutative: a*b equals b*a.

    The situation changes with int * int * size_t versus size_t * int * int as in C, multiplication is not associative. The first multiples int * int (with an int product), then does int * size_t. With select values, the first multiplication may overflow whereas size_t * int * int does not.

    When more than 2 objects may be multiplied, best to make certain the widest multiplication happens first and subsequently: example size_t * int * int.


    Is there any difference between these two?

    With only 2 objects to multiply, code in whatever way you like.
    I like to lead with the likely wider type.


    Since the cast is not needed and sizing to the object is easier to code right, review and maintain, consider:

    p = malloc(sizeof p[0] * 20);
    if (p == NULL) {
      TBD(); // Handle out-of-memory
    }