A.Sh A.Sh - 2 months ago 9
C Question

Have I used fscanf incorrectly?

I'm doing some coding in C for an assignment, and have encountered a strange problem. I have the following content saved in a txt-file:

11
1 1 0 1 0 0 0 1 0 0 0
0 1 1 0 1 0 0 0 1 0 0
0 0 1 1 0 1 0 0 0 1 0
0 0 0 1 1 0 1 0 0 0 1
1 0 0 0 1 1 0 1 0 0 0
0 1 0 0 0 1 1 0 1 0 0
0 0 1 0 0 0 1 1 0 1 0
0 0 0 1 0 0 0 1 1 0 1
1 0 0 0 1 0 0 0 1 1 0
0 1 0 0 0 1 0 0 0 1 1
1 0 1 0 0 0 1 0 0 0 1


It is just a square matrix of zeroes and ones, and the top number 11 is the dimensions of the matrix. I read this file using the following code snippet:

void generateCNF(FILE* f, FILE* g){
int n;
fscanf(f,"%d",&n);
int i,j;
int A[n][n]; // A is where I store my matrix
for(i=1;i<=n;i+=1){
for(j=1;j<=n;j+=1){
fscanf(f,"%d",&A[i][j]);
printf("%d ",A[i][j]); // I print out A while reading into it
}
printf("\n");
}
...
}


This is the output that printf generates:

0 1 1 0 1 0 0 0 1 0 0
0 0 1 1 0 1 0 0 0 1 0
0 0 0 1 1 0 1 0 0 0 1
1 0 0 0 1 1 0 1 0 0 0
0 1 0 0 0 1 1 0 1 0 0
0 0 1 0 0 0 1 1 0 1 0
0 0 0 1 0 0 0 1 1 0 1
1 0 0 0 1 0 0 0 1 1 0
0 1 0 0 0 1 0 0 0 1 1
1 0 1 0 0 0 1 0 44 0 1606415088


I have no idea how those last entries went so wrong. I tried opening the file with the matrix in a text editor, and it looked perfectly fine, so I suspect something is amiss with fscanf (or rather, my use of it).

I can add the complete C-file (around 90 lines) if that is necessary to help me, but I don't want to clutter the post unnecessarily.

Answer

You're indexing out of bounds of your array. If you don't crash, you're going to potentially get garbage because you're writing to memory you don't own. Arrays and Matrices in C are zero-indexed, so a size n by n matrix is indexed 0 through n-1.

for(i=1;i<=n;i+=1){
    for(j=1;j<=n;j+=1){

should be

for(i=0;i<n;i+=1){
    for(j=0;j<n;j+=1){
Comments