But in C I don’t know how to create a list without specifying a fixed dimension.
Lists like Python do not exist in the C language. There are only simpler data structures.
You need to create your own data structure if you want a dynamic list that holds any number of elements. The programmers who wrote Cpython did the same thing.
How to create a list that can receive elements up to the EOF, to use in the example code above?
You need to allocate the right amount of memory to store all the elements. The quantity of items shall only be revealed during the implementation of the programme when getchar()
returns EOF
.
To solve this, it is necessary to create a data structure that is able to dynamically expand its capacity during the execution of the algorithm:
struct lista {
size_t quantidade;
size_t capacidade;
char *elementos;
} lista;
Using the function malloc
, we can ask the operating system to allocate an initial amount of memory to our list:
#define CAPACIDADE_INICIAL 8
lista.quantidade = 0;
lista.capacidade = CAPACIDADE_INICIAL;
lista.elementos = malloc(CAPACIDADE_INICIAL);
We can then read the elements one by one until we receive EOF
:
int retorno;
while (EOF != (retorno = getchar())) {
lista.elementos[lista.quantidade++] = retorno;
}
The list initially has 0 elements and capacity for 8 elements. You can use the element counter as the list index, incrementing it every time an element is added.
What happens when the amount equals the capacity? It means that we have reached the limits of the current list and we will need to expand the memory it behaves before adding new elements.
It is possible to do this with the function realloc
:
if (lista.quantidade >= lista.capacidade) {
lista.capacidade += CAPACIDADE_INICIAL;
lista.elementos = realloc(lista.elementos, lista.capacidade);
}
Every time the list gets full up to its maximum capacity, the system expands that maximum capacity and allocates more memory so the list can hold that new maximum capacity.
When you receive EOF
, the list shall be filled in with all read elements and the code may continue writing the entries in reverse order.
Declare
array
as a pointer to int and make a dynamic allocation like malloc/calloc/realoc of <stdlib. h>.– anonimo
Search for dynamic memory allocation. For implementation, search for functions
malloc
,free
andrealloc
.– Woss
I read about these functions, but in the documentation it says that malloc
aloca o número especificado de bytes
, That doesn’t mean she still keeps a pre-defined limit?– Pirategull
You can, for example, allocate an element with malloc and to each new element you want to add make a realloc. Or use a chained list.
– anonimo