0

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;
}
epic_rain
  • 1
  • 3
  • 1
    You can `realloc` only space that that was dynamically allocated in the first place, which an (declared) array is not. Also, you are declaring `num` as an array of pointers, whereas you appear to want either an array of `int` or (since you have reallocation in mind) a pointer to `int`. – John Bollinger Apr 08 '22 at 14:05
  • Given a pointer to space that has been dynamically (re)allocated and not since freed, you can validly attempt to `realloc`ate the space to which it points. On success, it is reasonable and common to assign the resulting new pointer value to the variable that initially held the original. – John Bollinger Apr 08 '22 at 14:08
  • @JohnBollinger As far as i understand I do not need to create another array to hold the pointers to the reallocation and i need to change the nums to an allocated array of pointers (`int *`) am i missing sth? – epic_rain Apr 08 '22 at 14:30
  • That sounds about right, but your use of the plural in "pointer***s***" to the reallocation" makes me suspect that you still have a misunderstanding -- likely the same one that led you to write `int *nums[2]` in the first place. You are very unlikely to want an array of pointers, dynamically allocated or otherwise. You want a dynamically allocated array of `int`, to which there will be *one* pointer (value). – John Bollinger Apr 08 '22 at 14:40
  • @JohnBollinger I understood that i need to change ` int *nums[2]` to `int *ptr = (int*)malloc(2*sizeof(int))` which is allocating a space for two integers 8bytes instead of the static array used before – epic_rain Apr 08 '22 at 14:50
  • Very good, then. But note that you cannot call a function from file scope, outside any function. Therefore, you will need to wait until the beginning of `main()` to `malloc()` the initial space for that pointer. – John Bollinger Apr 08 '22 at 15:03
  • yes I only declared the pointer as a global variable before `main()` and then use `malloc` – epic_rain Apr 08 '22 at 15:21

1 Answers1

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;
}
TruthSeeker
  • 1,539
  • 11
  • 24
  • this is very helpful but I still have a question about the index how do you return the index of the last element added to the array assuming you can't use `currentIndex` is something like that possible or do I have to keep track of that too – epic_rain Apr 08 '22 at 15:44
  • @epic_rain: With this approach you must have `currentIndex`. Not optimal approach where you re-size the memory by one element every time insert is requested. It will have performance hit due to reallocation of new buffer and copy of the old data. – TruthSeeker Apr 08 '22 at 15:47
  • yes i understand but my question is there a way to find out the index of the last element with a value provided by the user assuming we `realloc` more than one element at a time – epic_rain Apr 08 '22 at 15:50
  • That depends on the type of user data. Suppose if the input is always positive integer and you can initialize unused part of array to zero or any negative integer. By tracking first marker element you can identify the size, though it increases time complexity. More over use of index element would be the right approach. – TruthSeeker Apr 08 '22 at 15:56
  • can you elaborate more I can't seem to get your point or please provide an example doc about this if possible – epic_rain Apr 08 '22 at 16:07
  • @epic_rain what exactly you wanted to achieve I'm not sure now. If you have any precise question I'm happy to answer. – TruthSeeker Apr 08 '22 at 16:20
  • [this](https://stackoverflow.com/questions/71800308/indexing-function-for-dynamic-arrays-in-c) – epic_rain Apr 08 '22 at 16:21