How would I allocate memory for 2d array with 3 rows and 8 coulmns?
Thanks
How would I allocate memory for 2d array with 3 rows and 8 coulmns?
Thanks
<type> **myArray;
myArray = malloc( sizeof( <type> ) * 24 );
Quzah.
Hope is the first step on the road to disappointment.
Hi Quzah,
Just wondering if you use a double pointer because of the two-dimensional array?
Code:#include "stdio.h" #include "stdlib.h" #include "time.h" #define ROWS 3 #define COLS 8 void fill_array (int **); /* fills array with random numbers */ void print_array (int **); /* prints array */ int main (void) { int i; int **table; table = malloc (ROWS * sizeof (int *)); /* allocates memory for pointers to each row (actually to first element in each row) */ for (i = 0; i < COLS; i++) table[i] = malloc (COLS * sizeof (int)); /* allocates memory for each row */ fill_array (table); print_array (table); return 0; } void fill_array (int **table) { int row, col; srand (time (NULL)); for (row = 0; row < ROWS; row++) for (col = 0; col < COLS; col++) *(*(table + row) + col) = rand() % 10; /* same as table[row][col] = rand() % 10; */ return; } void print_array (int **table) { int row, col; for (row = 0; row < ROWS; row++) { for (col = 0; col < COLS; col++) printf ("%4d", *(*(table + row) + col)); printf ("\n"); } return; }
Last edited by PutoAmo; 04-16-2002 at 06:42 AM.
Heh, Quzah's answer is way off, and PutoAmo's contains a bug
In main, it should be
Code:table = malloc (ROWS * sizeof (int *)); /* allocates memory for pointers to each row (actually to first element in each row) */ for (i = 0; i < ROWS; i++) // was COLS table[i] = malloc (COLS * sizeof (int)); /* allocates memory for each row */
#include "stdio.h"
Should be
#include <stdio.h>
> *(*(table + row) + col) = rand() % 10; /* same as table[row][col] = rand() % 10; */
Since there is no difference to the compiler, I usually go with the [row][col] syntax.