So, anyone know how to create a 2-d array using calloc? It seems to have been overlooked in my book.
So, anyone know how to create a 2-d array using calloc? It seems to have been overlooked in my book.
You could make an array of pointers and let each element be an array.
http://www.cs.cf.ac.uk/Dave/C/node11...00000000000000
Like so
Code:#include <stdio.h> #include <stdlib.h> #define ROWS 5 #define COLS 20 int main ( ) { int test[ROWS][COLS]; int **p; int row, col; /* allocate it */ p = calloc( ROWS, sizeof(int*) ); for ( row = 0 ; row < ROWS ; row++ ) { p[row] = calloc( COLS, sizeof(int) ); } /* use it */ for ( row = 0 ; row < ROWS ; row++ ) { for ( col = 0 ; col < COLS ; col++ ) { test[row][col] = p[row][col]; } } /* free it */ for ( row = 0 ; row < ROWS ; row++ ) { free(p[row]); } free(p); return 0; }
OK, I thought there would be a nice easy command to do it, but I guess not.
thanks for your help...
>OK, I thought there would be a nice easy command to do it
How is that not easy?
-Prelude
My best code is written with the delete key.
> The key word there is actually command
There is a one-liner, but it only works if COLS is a compile-time constant.
Perhaps you were thinking of some bloat language which does everything for you.
At some point, you've got to get into it at start doing things for yourself.