【问题标题】:Populating a dynamically allocated 2D array [duplicate]填充动态分配的二维数组
【发布时间】:2018-01-18 21:07:09
【问题描述】:

我正在尝试填充动态分配的二维数组。

具体来说,我正在尝试将随机数输入到数组中。

代码如下:

#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 而不是随机数。

【问题讨论】:

  • 注意:如果没有定义代码 j 直到像 for (int j = 0; j &lt; num_grades; ++j) 这样的循环,那么编译器会在 printf("%d ", array[i][j]); 上出错

标签: c random dynamic


【解决方案1】:

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

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]);
}

【讨论】:

  • 感谢您的光荣山丘之一。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    缩进不控制你的范围(例如在 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]);
    }
    

    【讨论】:

    • 非常感谢您发现这个简单的错误。
    猜你喜欢
    • 2016-08-07
    • 2016-04-01
    • 2019-02-26
    • 1970-01-01
    • 2016-06-08
    • 2013-11-24
    • 1970-01-01
    • 2021-02-03
    相关资源
    最近更新 更多