Hello all !
I am starting to use my new aquired (and limited) knowledge on dynamic memory. With this program I intend to allocate some memory from the program heap and use it for storing an array of randomly generated integers.
Function 'generate' prompts user for number of columns and rows. It then creates a unidimensional array of (col * row) elements (integers).
Function 'print' prints the array as a bidimensional array by accesing array ary.
When I try to execute it I keep getting a segmentation fault (core dumped) message. I will appreciate any help.
Thanks in advance and Merry Christmas !
Code :
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void generate (int *size, int *row, int *col, int *ary);
void print (int *ary, int size, int col);
int main (void)
{
int col;
int row;
int size;
int *ary = NULL;
generate (&size, &row, &col, ary);
print (ary, size, col);
return 0;
} /* main */
void generate (int *size, int *row, int *col, int *ary)
{
int i;
printf ("Number of rows: ");
scanf ("%d", row);
printf ("Number of columns: ");
scanf ("%d", col);
srand (time (NULL));
*size = *col * *row;
if (!(ary = (int *) (calloc (*size, sizeof (int)))))
exit (100);
for (i = 0; i < *size; i++)
*(ary + i) = rand () % 10;
return;
} /* generate */
void print (int *ary, int size, int col)
{
int i = 0;
while (i < size)
{
printf ("%3d", *(ary + i));
if (!((i + 1) % col) && i) /* last column */
printf ("\n");
i++;
} /* while */
return;
} /* print */