I create adjacent 2d arrays using the method posted here by Sean Chin. [1] [2] It works very well.
Briefly from the post:
char** allocate2Dchar(int count_x, int count_y) {
int i;
# allocate space for actual data
char *data = malloc(sizeof(char) * count_x * count_y);
# create array or pointers to first elem in each 2D row
char **ptr_array = malloc(sizeof(char*) * count_x);
for (i = 0; i < count_x; i++) {
ptr_array[i] = data + (i*count_y);
}
return ptr_array;
}
And the following free function:
void free2Dchar(char** ptr_array) {
if (!ptr_array) return;
if (ptr_array[0]) free(ptr_array[0]);
free(ptr_array);
}
Itβs not obvious to me how to create an equivalent redistribution function in any dimension, although I am only interested in redistributing the number of rows while maintaining continuity. A growing number of columns would be interesting to understand, but probably quite difficult. I did not find a direct discussion of this problem anywhere except to say: "This is difficult!". [2]
, , 1D- ( ) , 1D-, (ptr_array) . , , , , , , .
( , ). , ...
double **
reallocate_double_array (double **ptr_array, int count_row_old, int count_row_new, int count_col)
{
int i;
int old_size = count_row_old * count_col;
int new_size = count_row_new * count_col;
double *data = malloc (old_size * sizeof (double));
memcpy (&data[0], &ptr_array[0][0], old_size * sizeof (double));
data = realloc (data, new_size * sizeof (double));
free (ptr_array[0]);
free (ptr_array);
ptr_array = malloc (count_row_new, sizeof (double *));
for (i = 0; i < count_row_new; i++)
ptr_array[i] = data + (i * count_col);
return ptr_array;
}
, , , !
.
[1] 2D- ?
[2] http://www.eng.cam.ac.uk/help/tpl/languages/C/teaching_C/node52.html