Search code examples
carraysdynamic-memory-allocation

C style coding and dynamic arrays


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.


Solution

  • 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.