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

4
  • What does this mean? "So I want to create dynamic array a[]. without changing static array." Commented Apr 24, 2020 at 4: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. Commented Apr 24, 2020 at 4:52
  • Once an array is defined, it size cannot change. Instead allocate memory for an array. Commented Apr 24, 2020 at 5: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. Commented Apr 24, 2020 at 5:21

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.