#include #include /* * C does not have new and delete * instead you use malloc and free, and realloc */ /* * examples of passing dynamic arrays to functions * and manipulating the values */ void init ( int ** arr, const int rows, const int cols ) { int i,j,k = 0; for ( i = 0 ; i < rows ; ++i ) for ( j = 0 ; j < cols ; ++j ) arr[i][j] = ++k; } void print ( int ** arr, const int rows, const int cols ) { int i,j; for ( i = 0 ; i < rows ; ++i ) { for ( j = 0 ; j < cols ; ++j ) printf ( "%3d ", arr[i][j] ); printf( "\n" ); } } int main() { { /* allocate an array of ints */ int i; int size = 10; int * arr = ( int * ) malloc ( sizeof ( int ) * size ); /* use it */ for ( i = 0 ; i < 10 ; ++i ) arr[i] = 10 - i; for ( i = 0 ; i < 10 ; ++i ) printf( "%d ", arr[i] ); printf( "\n" ); /* growing arrays is easy with realloc */ size += 10; arr = ( int * ) realloc ( arr, sizeof ( int ) * size ); for ( i = 10 ; i < 20 ; ++i ) arr[i] = 30 - i; for ( i = 0 ; i < 20 ; ++i ) printf( "%d ", arr[i] ); printf( "\n" ); /* free them when you are done */ free ( arr ); } { /* allocate a 2D array of ints */ int i; int rows = 5; int cols = 4; int ** arr = ( int ** ) malloc ( sizeof ( int * ) * rows ); for ( i = 0 ; i < rows ; ++i ) arr[i] = ( int * ) malloc ( sizeof ( int ) * cols ); /* use it */ init ( arr, rows, cols ); print ( arr, rows, cols ); /* free them when you are done */ for ( i = 0 ; i < rows ; ++i ) free( arr[i] ); free( arr ); } { /* another (nicer) way to allocate a 2D array of ints */ int i; int rows = 6; int cols = 10; int * tmp = ( int * ) malloc ( sizeof ( int ) * rows * cols ); int ** arr = ( int ** ) malloc ( sizeof ( int * ) * rows ); for ( i = 0 ; i < rows ; ++i ) arr[i] = tmp + i * cols ; /* use it */ init ( arr, rows, cols ); print ( arr, rows, cols ); /* free them when you are done */ free( arr ); free( tmp ); } return 0; }