It all depends on the coding style. There are several styles.
To answer the question, people write
malloc(n * sizeof(char))
save all your code that malloc uses. Next time they may need an int , and then they can write the code in the same way
malloc(n * sizeof(int))
So the reason this is being done is to keep the coding style consistent. Despite the fact that sizeof(char) really always guaranteed to be 1, and therefore it is superfluous. This is a way to write self-documenting code.
However, the most common way to use malloc in C is perhaps
type* t = malloc(n * sizeof(*t));
or 100% equivalent:
type* t = malloc(n * sizeof *t);
Since the sizeof operator is not evaluated for side effects, this code is safe, although the variable t is not yet initialized.
The third possible style is pedantically correct, which the pointers of the array will use, because what we select is actually an array:
type (*t)[n] = malloc( sizeof(type[n]) );
This is perhaps the most correct way, since it concerns the correctness of the text. The size of the array is allocated, and we point to the selected array with an array pointer.
However, the problem with this style is that array pointers add extra complexity to the syntax: you will need to cancel this array as (*t)[i] instead of t[i] . This makes it difficult to read the code. (And also, as a note, if n is not an integer constant expression, the code will not compile on older legacy C compilers.)
Lundin Oct 27 '17 at 13:02 on 2017-10-27 13:02
source share