What is the difference between Static and Dynamic arrays in C++?

Static arrays are created on the stack, and have automatic storage duration: you don’t need to manually manage memory, but they get destroyed when the function they’re in ends. They necessarily have a fixed size at compile time: int foo[10]; Arrays created with operator new[] have dynamic storage duration and are stored on the heap … Read more

When and why to use malloc?

malloc is used for dynamic memory allocation. As said, it is dynamic allocation which means you allocate the memory at run time. For example when you don’t know the amount of memory during compile time. One example should clear this. Say you know there will be maximum 20 students. So you can create an array … Read more

Difference between static memory allocation and dynamic memory allocation

This is a standard interview question: Dynamic memory allocation Is memory allocated at runtime using calloc(), malloc() and friends. It is sometimes also referred to as ‘heap’ memory, although it has nothing to do with the heap data-structure ref. int * a = malloc(sizeof(int)); Heap memory is persistent until free() is called. In other words, … Read more

How can i create dynamically allocated array In C [duplicate]

Assuming you have the number of rows “r” and the number of columns “c”, you can do this: int **arr; arr = malloc(r*sizeof(int*)); for(int i=0; i < r; i++) { arr[i] = malloc(c*sizeof(int)); } this dynamically allocates an array of pointers to integers, and then allocates arrays of integers to each pointer. Don’t forget to … Read more