Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Dynamic Memory allocation for arrays

Tags:

People also ask

Is dynamic memory allocation possible in array?

Once the size of an array is declared, you cannot change it. Sometimes the size of the array you declared may be insufficient. To solve this issue, you can allocate memory manually during run-time. This is known as dynamic memory allocation in C programming.

Which function is used to dynamically allocate memory to arrays?

C malloc() method The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form.

How do you dynamically declare an array?

Dynamic arrays in C++ are declared using the new keyword. We use square brackets to specify the number of items to be stored in the dynamic array. Once done with the array, we can free up the memory using the delete operator. Use the delete operator with [] to free the memory of all array elements.


How am I supposed to use dynamic memory allocations for arrays?

For example here is the following array in which i read individual words from a .txt file and save them word by word in the array:

Code:

char words[1000][15];

Here 1000 defines the number of words the array can save and each word may comprise of not more than 15 characters.

Now I want that that program should dynamically allocate the memory for the number of words it counts. For example, a .txt file may contain words greater that 1000. Now I want that the program should count the number of words and allocate the memory accordingly.

Since we cannot use a variable in place of [1000], I am completely blank at how to implement my logic. Please help me in this regard.