malloc vs calloc

The three memory allocation statements you’ve shown:

arr = (int *)malloc(nx * sizeof(int));
arr = malloc(nx * sizeof(int));
arr = calloc(nx, sizeof(int));

all serve the purpose of dynamically allocating memory for an array of nx integers. However, there are key differences in terms of syntax, behavior, and intent:


*1. (int )malloc(nx * sizeof(int))

Type-casted malloc

→ Best practice in C: Avoid casting malloc.


2. malloc(nx * sizeof(int))

Raw malloc without casting

→ This is preferred in modern C code.