arraysmemorymallocprogramming-languagesdynamic-memory-allocation

Does mallocing a space of 3*sizeof(float) and creating an array of floats of size 3 do the basically the same thing in C?


My question is if writing this line: float* array = malloc(3*sizeof(float)); Is equivalent of writing: float array[3]; If not, why?

(i'm reaaally new to C)

I noticed that when i try to manipulate the elements of each case it works well, but i'm skeptic of believing that it is literally the same thing written in another way in a lower-level (or even higher)


Solution

  • calloc initializes the memory to 0 as opposed to malloc whose returned block of memory is uninitialized. There could also be a difference in performance (speed here) for which malloc can be faster than calloc. Lastly, you may be concerned over which memory is used for allocation. There is a similar question I saw for which there is a great answer already (I can't comment so I put it in a answer myself instead).

    The returned block of memory can be accessed just fine with using either function as you described with your array example in the question.