I want to grow an array at runtime (without predining the length with a macos)
I have the following questions
I tried the following code (and expecting 012
as output) but get 000
#include <stdlib.h>
#include <stdio.h>
int main()
{
int *arr = NULL;
size_t n = 0;
for (int i = 0; i < 3; ++i) {
arr = realloc(arr, (n + 1) * sizeof *arr);
arr[n++] = i;
printf("%d", *arr);
}
}
OP's mostly has it.
It is just printing the first element each time.
// printf("%d", *arr);
printf("%d", arr[n-1]);
is it possible to do it with an array?
No. In C an array cannot change size once it is defined.
The memory size allocated and referenced by a pointer can change though.