Search code examples
arrayscpointersmallocrealloc

How to grow a pointer or an array in C at runtime (without knowing the end length at compile time)


I want to grow an array at runtime (without predining the length with a macos)

I have the following questions

  1. is it possible to do it with an array?
  2. If not shall I use a pointer to int?

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);
    } 
}

Solution

  • 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.