I am trying to use malloc to allocate the inner section of a dynamically allocated 2D array. I know that vectors and new are better but I am required to use malloc and realloc. I start off with two variables.
buffer_count = 0
buffer_size = 3
I then create the 2D array of size [3][26](each inner array just has to be of size 26).
Here is that creation:
int ** array_creation (){
int ** arr = (int **) malloc(buffer_size * sizeof(int *));
for(int i=0;i<buffer_size;i++){
arr[i] = (int *)malloc(26 * sizeof(int));
}
}
Every time I add to the next array location I increase the buffer_count. When the count is equal to the size, I am trying to double the size of the outer part of the array.
if(buffer_count >= buffer_size){
buffer_size = buffer_size * 2;
arr = (int **) realloc(*arr, buffer_size *sizeof(int));
for(int i=0;i<buffer_size;i++){
arr[i] = (int *)malloc(26 * sizeof(int));
}
This code above will run but it will obviously write over the first 3 since I am using malloc in the inner for loop.
Any attempt at only adding from say buffer_count / 2 and so on and make the inner for loop arr[I] be something like arr[buffer_size/2] to start from the end of what was already allocated to not overwrite it I get a Segmentation Error. I have also tried doing something like:
if(arr[i] == NULL){
//write to array
}
That also does not work. Like I said, I know the draw backs of using malloc in C++ but I am required to here. Thank you