I am trying to populate a dynamically allocated 2D array.
Specifically, I am trying to input random numbers into an array.
Code below:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int i, j, num_students = 10, num_grades = 4;
int **array;
srand(time(NULL));
array = malloc(sizeof(int *) * num_students);
for (i = 0; i < num_students; ++i)
array[i] = malloc(sizeof(int) * num_grades);
for (i = 0; i < num_students; ++i)
{
printf("Student %d has grades: ", i);
for (j = 0; j < num_grades; ++j)
array[i][j] = rand() % 101;
printf("%d ", array[i][j]);
printf("\n");
free(array[i]);
}
free(array);
return 0;
}
The output:
Student 0 has grades: 0
Student 1 has grades: 0
Student 2 has grades: 0
Student 3 has grades: 0
Student 4 has grades: 0
Student 5 has grades: 0
Student 6 has grades: 0
Student 7 has grades: 0
Student 8 has grades: 0
Student 9 has grades: 0
I do not know why it is printing 0 instead of the random numbers.
Aucun commentaire:
Enregistrer un commentaire