2D数组-我想查找每行中哪些列中包含1

时间:2018-11-12 21:17:26

标签: c arrays

我的输入看起来像这样:

15 5
0 0 1 0 0
0 0 1 0 0
0 0 1 0 0
0 0 0 0 0
0 0 0 0 0
1 0 0 0 0
0 1 0 1 0
0 0 1 0 0
0 0 0 0 1
0 0 0 0 0
0 0 0 0 0
0 1 0 0 0
1 0 0 0 1
0 0 1 0 0
0 0 0 1 0

第一行包含数组的行数和列数。基本上我想找出这些1在数组中的位置。

因此,在前三行中,我想获得3,在第七行中,我想获得1,等等。

到目前为止,我的代码看起来像这样

2 3

我的输出是这样

#include <stdio.h>

int main() {

int row, column;

FILE* input;
FILE* output;

input = fopen("input.txt", "r");

if (input == 0) {
    printf("ERROR couldn't open input.txt");
    return 1;
}

if (! fscanf(input, "%d %d", &row, &column)) {
    printf("ERROR not recognised value");
    fclose(input);
    return 2;
} 

output = fopen("output.txt", "w");

int meteor[row][column];

    for (int i = 0; i < row; i++) {
        for (int j = 0; j < column; j++) {
            fscanf(input, "%d", &meteor[i][j]);
        }
    }
int sum;
int loc[row];
    for (int i = 0; i < row; i++) {
        sum = 0;
        for (int j = 0; j < column; j++) {
            sum += meteor[i][j];
            if (meteor[i][j] == 1) {
            loc[i] = (j + 1);
            }
        }
        printf("%d %d\n", loc[i], sum);
    }

fclose(input);
fclose(output);

return 0;
}

第一列显示了一些位置,第二列显示了行中有多少个1,但是当行中只有3 1 3 1 3 1 0 0 -1 0 1 1 4 2 3 1 5 1 0 0 4214921 0 2 1 5 2 3 1 4 1 或有多个0s时,所有操作都会失败。而且我也想存储这些值。

1 个答案:

答案 0 :(得分:0)

您需要初始化loc[]。如果仔细查看代码,只会在if (meteor[i][j] == 1)的情况下填充它……但您会为i的每个索引打印它。会打印未初始化的内存(即未知)。

如果要存储“和”,请回答问题的第二部分。像loc[]一样简单地使meteor成为2d数组,但是具有2列(行和总和)。即int loc[row][2] ..当然要初始化两列:)