填充动态分配的2D数组

时间:2018-01-18 21:07:09

标签: c random dynamic

我正在尝试填充动态分配的2D数组。

具体来说,我试图将随机数输入数组。

以下代码:

#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;

}

输出:

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 

我不知道为什么打印0而不是随机数。

3 个答案:

答案 0 :(得分:3)

你错过了{ ... } ...

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

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

,但它应该是

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

答案 1 :(得分:1)

你在内部for循环周围缺少括号:

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

答案 2 :(得分:1)

缩进不会控制您的范围(例如,在Python中)。你的for循环只遍历第一行:

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

确保您已将这两行封装在大括号中:

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