'How to use realloc multiple times in a program

I am confused about how to use realloc to add space for other elements in the array nums

when the program first starts it has space for two elements but if the user wants to add more elements it will cause a segfault, this means we need to create a bigger array with 3 or more elements and add them one by one for the old one until index 1 and take a user-provided integer for the third element in the array

If the program is supposed to run in a while loop which never ends unless the user kills the process means we have to use realloc every time the array gets full that said my confusion starts here

do I have to make another array that will hold the address of realloc since we need to free it later on or can it use the same pointer for multiple realloc uses

int *nums[2];



int numsSize()
{
  return sizeof(nums)/sizeof(int*);
}

//return index at which user added elements end 
int numsIndex()
{
  for (int i = 0 ; i < numsSize(); i++)
  {
    if (!nums[i])
    {
      return i;
    }
  }
  return numsSize();
}


void numsResize()
{
// resize nums to have space for 4 elements  
}

int main(void) {

  nums[0] = 10 ; 
  printf("Size of array : %d \n", numsSize()); // outputs 2

  printf("Index of last added element in array : %d\n", numsIndex()); // outputs 1 
  
  return 0;
}


Solution 1:[1]

If I understand the question correctly, you need to allocate a memory dynamically.

  1. int *nums[2]; is fixed size array of pointer, you can't grow it dynamically.
  2. nums[0] = 10 ; is invalid statement.

DEMO

#include <stdlib.h>
#include <stdio.h>

int *ptr = 0;
int size;
int currentIndex;

void
initialize ()
{
  if (ptr)
    return;

  size = 2;
  ptr = malloc (sizeof (int) * size);
  
  if(!ptr)
      exit(0);

  currentIndex = 0;
}

void
unInitialize ()
{
  if (ptr)
    free (ptr);

  size = 0;
  currentIndex = 0;
}

void
doubleTheSize ()
{
  ptr = realloc (ptr, sizeof (int) * size * 2);

  if(!ptr)
      exit(0);
  size = size * 2;
}

void
AddElement (int element)
{
  if (currentIndex >= size)
    doubleTheSize ();

  ptr[currentIndex] = element;
  ++currentIndex;

}

void
printInput ()
{
  for (int i = 0; i < currentIndex; ++i)
    {
      printf ("%d ", ptr[i]);
    } printf ("\n");
}

int
main (void)
{

  initialize ();
  int i = 0;

  do
    {
      printf ("Enter Element :");
      scanf (" %d", &i);

      //condition to break the loop
      if (i == -1)
          break;

      AddElement (i);
      printInput ();
    }
  while (1);


  unInitialize ();

  return 0;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1