0

I'm learning C and I'm wondering what is the point of sizeof(char) *100 in

char *temp = (char*) malloc(sizeof(char) * 100);

I understand the sizeof(char) to be 1, so why we can't just write malloc(100)?

Thanks

Daniel
  • 23
  • 2
  • 3
    We can. This is just a general form that is used for other types too / matter of style. – Eugene Sh. May 28 '21 at 16:05
  • Daniel: Your intuitions are good. The multiplication by `sizeof(char)` is unnecessary. Unfortunately, lots of people convince themselves (wrongly) that it's necessary for some reason. So you'll see it in lots of code. – Steve Summit May 28 '21 at 16:08
  • The `char* ` cast is also unnecessary and bad practice. Suggest: `char *temp = malloc( sizeof(*temp) * 100 ) ;` That allows you to change the type of `temp` without needing two corresponding changes. If you are "learning C" choose your sources carefully - there is probably more bad code than good out there; just picking code at random will lead to cargo-cult programming. – Clifford May 28 '21 at 22:16

1 Answers1

1

There's no point to using sizeof(char) in this case.

The C standard defines sizeof(char) to be 1, so better to just use malloc(100).

Also, don't cast the return value of malloc.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • 3
    There is a point to using `sizeof(char)`. You may prefer not to, but it is not correct to say there is no point. Making the type evident makes it more visible when the code is edited to work with other types, such as wide characters. A human is less likely to overlook the required change when the type is explicit. Preferably, one would use `malloc(100 * sizeof *temp)`, making the type automatic in respect to the thing being allocated. But still there is an advantage to expressing the type explicitly, akin to saying the length of a box is 3 feet versus saying it is 3. – Eric Postpischil May 28 '21 at 16:08