1

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.

elMentat
  • 186
  • 1
  • 9
  • 1
    Note: Had code not defined `j` until the loop like `for (int j = 0; j < num_grades; ++j)`, then the compiler would have error-ed on `printf("%d ", array[i][j]);` – chux - Reinstate Monica Jan 18 '18 at 21:16

3 Answers3

3

You missed the { ... }...

for (j = 0; j < num_grades; ++j)
        array[i][j] = rand() % 101;
        printf("%d ", array[i][j]);

Is the same as

for (j = 0; j < num_grades; ++j) {
        array[i][j] = rand() % 101;
}
printf("%d ", array[i][j]);

,but it should be

for (j = 0; j < num_grades; ++j) {
        array[i][j] = rand() % 101;
        printf("%d ", array[i][j]);
}
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
1

You're missing brackets around the inner for loop:

for (j = 0; j < num_grades; ++j)
{
    array[i][j] = rand() % 101;
    printf("%d ", array[i][j]);
}
Mike Holt
  • 4,452
  • 1
  • 17
  • 24
1

Indentation doesn't control your scope (as it does in Python, for example). Your for-loop only iterates over the first line:

for (j = 0; j < num_grades; ++j)
    array[i][j] = rand() % 101; // <- only this is iterated over
    printf("%d ", array[i][j]); // <- this only runs once, after the for-loop

Ensure that you've encapsulated both lines in braces:

for (j = 0; j < num_grades; ++j) {
    array[i][j] = rand() % 101;
    printf("%d ", array[i][j]);
}
frslm
  • 2,969
  • 3
  • 13
  • 26