Home c Dynamic array of characters in C

Dynamic array of characters in C [duplicate]




How to create a dynamic array of characters (the size of the array is determined during input) in C?

Answer 1, authority 100%

There are no dynamic arrays in C itself, but the functions of the standard library malloc, free and realloc allow you to implement an array of variable size:

int * mas = (int *) malloc (sizeof (int) * n); // Create an array of n elements of type int
 mas = (int *) realloc (mas, sizeof (int) * m); // Resize the array from n to m while preserving the contents
 free (mas); // Free memory after using the array

The disadvantage of this approach is the need to calculate the size of the allocated memory, apply an explicit type conversion, and carefully monitor the lifetime of the array (as is always the case when working with dynamically allocated memory in C).

Dynamic memory allocation should help.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions