简体   繁体   中英

Getting 2d char array dimensions and content from a text file C

There are a lot of questions like this in stack, but I could not find one on the specific issue thus I decided to post..
I get my input from a text file which is always structured like this:

X Y
A1 A2 AY
A4 A5 ..
AX .. ..

Dimensions of a 2d array on the first line and a 2d array composed of characters with X rows and Y columns.
Something goes wrong while transitioning from the first row of the text file to the rest.
My code for the input is the following:

#include<stdio.h>
#include<stdlib.h>

int n,m;

int main(int argc,char **argv){
    if(argc!=2){
            perror("Error: ");
            return EXIT_FAILURE;
    }
    FILE* txtfile=fopen(argv[1],"r");
    if(txtfile<0){
            perror("Error: ");
            return EXIT_FAILURE;
    }
    char lab[n][m];
    fscanf(txtfile,"%d %d",&n,&m);
    for(int i=0; i<n; i++){
            for(int j=0; j<m; j++){
                    fscanf(txtfile," %c",&lab[i][j]);
            }
    }

An example input is the following:

3 3
ULD
LUD
LRL

Which produces the result:

lab[0][0] = L
lab[0][1] = R
lab[0][2] = L
lab[1][0] = L
lab[1][1] = R
lab[1][2] = L
lab[2][0] = L
lab[2][1] = R
lab[2][2] = L

Which is obviously wrong... If I provide n,m through user input through the terminal or give them a value inside my program (n=3 and m=3 in this case), and remove them from the text file:

ULD
LUD
LRL

I then get the correct 2d array:

lab[0][0] = U
lab[0][1] = L
lab[0][2] = D
lab[1][0] = L
lab[1][1] = U
lab[1][2] = D
lab[2][0] = L
lab[2][1] = R
lab[2][2] = L

I have tried using fseek to move the pointer in the file to the second line after the first is read, but without results.
Any help/explanation is appreciated, I'm still new to C.

Well, answering my own question, and to learn from my own stupidity... I declared the character array before actually assigning values to n,m resulting in a "broken array". I spent half a day thinking it was some convoluted C pointer thing I was missing, but turns out it was just an amateur mistake... Literally figured 5 minutes after posting...

char lab[n][m];
fscanf(txtfile,"%d %d",&n,&m);

Is wrong and should be:

fscanf(txtfile,"%d %d",&n,&m);
char lab[n][m];

I will keep the questiοn undeleted in case anyone else does the same stupid mistake...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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