0

This question is regarding malloc in C associated with structs or arrays. I noticed there are 2 ways to allocate memory and I cannot tell the difference between them.

char* arr = (char*) malloc(capacity * sizeof(char));

versus

char* arr =  malloc(capacity * sizeof(char));

What is with the extra (char*)? The code compiles fine without it and executes the same results.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
T-Bone
  • 45
  • 4

2 Answers2

0

In C++ you need to do the (char*) cast, but when compiled for C, void* will freely convert to any other pointer type.

If the code is potentially shared between the languages, then putting the cast in costs nothing.

Gem Taylor
  • 5,381
  • 1
  • 9
  • 27
0

The function malloc returns a void pointer to the beginning of the allocated memory block. In C, void pointers can be implicitly and explicitly casted to any type, that's why those two lines of code are essentially identical in C.

Javier Silva Ortíz
  • 2,864
  • 1
  • 12
  • 21