Lobs001 Lobs001 - 1 year ago 131
C Question

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

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..

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.

Any help would be greatly appreciated. Thanks!

Answer Source

It compiles, but then crashes

You should use address of array in scanf like

     fscanf_s(stream, "%d", &array[a][b]);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download