c - How to reallocate memory for a 2-dimensional array? -


I was trying to implement Viterbi decoder in C

so I had a 2-dimensional Here is the sample code for the dynamically created 2D array, which I wanted to create dynamically:

  place_table = (int **) malloc ((no_places + 1) * Sizeof (int *)); For (i = 1; i & lt; = no_places; i ++) place_table [i] = (integer *) malloc ((no_places + 1) * sizeof (int));  

The size of this 2-dimensional array varies in my decoder, i.e., no_places remains different, so I wanted to know how to memory Reload 2-dimensional array

Any suggestions or help will be highly appreciated.

You can allocate memory dynamically in the form of 2-D array (C 99) For:

  int no_places; Int n = no_places + 1; // For short the following statement int (* place_table) [n] = malloc (sizeof (int [n] [n])); // if check for zero (place_table == NULL) {// there is a problem / it is handle} other {// you are good to go}  

this is correct Will not be allocated the memory for the 2-D array place_table , because with the change in the dimension, the value of the old array will be redefined as if it were the elements of the new array. This will cause rows to wrap around (courtesy Pete Kirkham). Therefore, you need to allocate a new array and need to copy the values ​​from the old array, then free the old array.

  int old_n = n; // n has changed the value // New array int (* new_place_table) [n] = allocate malloc (sizeof (int [n] [n])); // Check for NULL and proceed accordingly // If there is no zero, copy the copy for location_title (for int i = 0; i & lt; old_n; i ++) {for (int j = 0; j & lt; old_n; j ++) {new_place_table [I] [j] = location_table [i] [ja]; }} Free (location_table); // work with new_place_table free (new_place_table);  

Also keep in mind that you do not need to insert the results of malloc . There is no use to do this and if you forget to include the stdlib.h header file, then this bug, undefined behavior and program crashes may be read.


Comments