简体   繁体   English

从C中的文件中读取2D数组

[英]Read 2D array from file in C

I know this has been both answered and asked before, but I can't quite understand the answers given in those posts, so I feel like I have no option but to ask it myself. 我知道这已经得到了回答和问过,但我不太明白这些帖子中给出的答案,所以我觉得我别无选择,只能亲自问问。 It's definitely a beginner's question so please bear with me and don't get overly complicated unless it's absolutely needed. 这绝对是一个初学者的问题,所以请耐心等待,除非绝对需要,否则不要过于复杂。

What I want to do is to read a 2x3 matrix from a .txt file, such as 我想要做的是从.txt文件中读取2x3矩阵,例如

12 14 15
24 244 988

and then store it in a 2D array, let's call it "array", so that array[0][0] would = 12, and array[1][1] = 244 etc.. 然后将它存储在2D数组中,我们称之为“数组”,这样数组[0] [0]将= 12,数组[1] [1] = 244等。

What I've come up with so far is simply this: 到目前为止我想出的只是这个:

for (int a = 0; a < 2; a++) {
        for (int b = 0; b < 3; b++) {
                fscanf_s(stream, "%d", array[a][b]);
        }

}

It compiles, but then crashes, so I'm not sure what's wrong exactly. 它编译,然后崩溃,所以我不确定究竟是什么错。 It both compiles and runs perfectly if I remove that fscan_s statement so the problem has to be there. 如果我删除那个fscan_s语句,那么它编译和运行都很完美,所以问题必须存在。

Any help would be greatly appreciated. 任何帮助将不胜感激。 Thanks! 谢谢!

It compiles, but then crashes 它编译,然后崩溃

You should use address of array in scanf like 你应该在scanf使用数组的地址

     fscanf_s(stream, "%d", &array[a][b]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM