Reputation:
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).
Upvotes: 0
Views: 2470
Reputation: 25
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
Upvotes: 0
Reputation: 48572
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);
.
Upvotes: 4