Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to use double for loop for 2 dimensional array in C?
    text
    copied!<p>I'm new to C and having trouble with pointers and 2D arrays. I have a file that I want to read values from and insert them into a 2D array. the file is formatted such that the first 2 digits are the number of rows and columns respectively, and the rest of the digits on the line fill up the matrix. Currently it reads the row and column values fine, and the first row of digits, but doesn't continue after that. What's going wrong? I'm assuming I screwed up something with pointers, or I am missing something in my understanding of 2D arrays in C.</p> <p>Code:</p> <pre><code>#define MAXSIZE 10 FILE *fpin .. int RdRowSize() { int row = 0; fscanf(fpin, "%d", &amp;row); return row; } int RdColumnSize() { int col = 0; fscanf(fpin, "%d", &amp;col); return col; } void RdMatrix(int *row, int *col, int matrix[][MAXSIZE]) { int i = 0, j = 0; *row = RdRowSize(); *col = RdColumnSize(); for(i ; i &lt; *row ; i++) { for(j ; j &lt; *col ; j++) { fscanf(fpin, "%d", &amp;matrix[i][j]); /* this stops after i = 0 for some reason? */ } } } void PrMatrix(int row, int col, int matrix[][MAXSIZE]) { int i = 0, j = 0; for (i ; i &lt; row ; i++) { fprintf(stdout," "); for (j ; j &lt; col ; j++) { fprintf(stdout, "%5d ", matrix[i][j]); } fprintf(stdout, "\n"); } fprintf(stdout, "\n"); } int main() { int A[MAXSIZE][MAXSIZE]; int rowA = 0, columnA = 0; RdMatrix(&amp;rowA, &amp;columnA, A); PrMatrix(rowA, columnA, A); .. } </code></pre> <p>The contents of fpin:</p> <pre><code>3 3 0 6 4 2 2 5 4 5 0 </code></pre> <p>Which should read rowA = 3, rowB = 3 (which it does) then fill the matrix with the rest of the numbers, but it stops after the first row. When I print the matrix I get this:</p> <pre><code>**** MATRIX **** Size = 3 x 3 0 6 4 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload