Automatic growth in two-dimensional arrays

In C, there is a way to automatically create an array. For instance:

int arr [100] [10]; 

If the array is full, is it possible that it "automatically" becomes larger? Or this is only possible if you are using C ++. How do you write this in C?

+4
source share
2 answers

There is no such function in C: you have to declare the array using pointers, manually define the condition β€œarray is full”, call malloc , make a copy in the extended array and free original one. Even arrays of variable length will not work, because they only allow you to set their size once during the lifetime of the array.

In C ++, you can use std::vector<std::vector<int> > instead of a simple array. You still need to define the condition that the array is full, but the std::vector<T> container will take care of all the redistributions and extensions when you resize it for you.

+2
source

"automatic" growth of any array in C is not possible. If you declare an array statically:

 int arr[10]; 

you have as many memory locations as you indicated. If you want to change it at run time, you need to declare it dynamically with malloc() and make it larger with realloc()

A quick example for you:

 int main(void){ int input, count = 0, length = 2; int * arr = malloc(sizeof(int) * length); // array of size 2 while((input = getchar()) != 'q') //get input from the user { getchar(); //get rid of newlines arr[count] = input; if(count + 1 == length){ // if our array is running out of space arr = realloc(arr, length * length); // make it twice as big as it was length *= length; } count++; } for(length = 0; length < count; length++) // print the contents printf("%d\n", arr[length]); free(arr); return 0; } 
+1
source

Source: https://habr.com/ru/post/1445121/


All Articles