0

I really don't know how to create a dynamic array in c. This is a quick example. If I define a static array then a buffer overflow is basically set. So How Do I create a dynamic array which I can use in a for loop? Is malloc a good idea? And if it is, how do i use malloc in a for loop?

int my_array[] = {};
int i = 10;
for (i; i <= sizeof(my_array) / sizeof(my_array[0]); i++) {
   my_array[i] = i + 2;
}

1 Answers1

2

Not only is malloc a good idea, it is the preferred way to dynamically allocate memory in C. The function is defined here, where also an example can be found. Note that free should be used to deallocate the memory once it is not needed anymore.

Codor
  • 17,447
  • 9
  • 29
  • 56