0

Suppose say I have a static array

int a[10];

At some point the the program I want to insert 11th element.So it will throw error as Index out of range error.

So I want to create dynamic array a[]. without changing static array. And I want to take more input to array a[] during run time (means scalability).

Roberto Caboni
  • 6,699
  • 10
  • 24
  • 37
  • What does this mean? "So I want to create dynamic array a[]. without changing static array." – enhzflep Apr 24 '20 at 04:49
  • "So it will throw error as Index out of range error." It will do no such thing. You'll just overwrite random memory and create a security bug, with no safety net to warn you. – Joseph Sible-Reinstate Monica Apr 24 '20 at 04:52
  • Once an array is _defined_, it size cannot change. Instead allocate memory for an array. – chux - Reinstate Monica Apr 24 '20 at 05:14
  • @JosephSible-ReinstateMonica It has undefined behavior. Throwing an out of range error (whatever "throwing" might mean in C) is one of infinitely many possibilities. Most likely it will clobber memory outside the array -- unless the compiler has optimized the code based on the assumption that its behavior is defined. – Keith Thompson Apr 24 '20 at 05:21

2 Answers2

4

Replace int a[10]; with int *a = malloc(10 * sizeof(int));. When you want to expand it to 11 elements, do a = realloc(a, 11 * sizeof(int));. If either of the previous two functions return null, then you ran out of memory and should treat it like the error that it is. Finally, where your original array would have gone out of scope, put free(a);.

  • 3
    A nice alternative to `realloc(a, 11 * sizeof(int))` is `realloc(a, 11 * sizeof *a)`. Easier to code right, review and maintain with its no "did code use the right type?" error. – chux - Reinstate Monica Apr 24 '20 at 05:16
0

I don’t think you can increase array size statically in C.

When it comes to static - we cannot increase the size of an array dynamically since we will define its size explicitly at the time of declaration itself. However you can do it dynamically at runtime using the realloc() in stdlib.h header. but when you create an array dynamically using malloc().

The typical response in this situation is to allocate a new array of the larger size and copy over the existing elements from the old array, then free the old array.
There are some resources which may help you to understand this. here

Shiv Sharma
  • 25
  • 1
  • 5