TL;DR: Struggling with 2 dimensional arrays.
I'm trying to create two two dimensional array from a list of integers from a text file. This is programmed in C.
tester.txt contains:
2 1 2 3 4 5 6 7 8
The first number means that both arrays have 2 rows and 2 columns, if it were any other number the columns/rows would be represented as such.
tester.txt should ouput the following:
1 2 5 6
3 4 7 8
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i,j,k;
FILE *filepointer;
int nrows;
int size;
fputs("Enter a filename: ", stdout);
fflush(stdout);
if ( fgets(filename, sizeof filename, stdin) != NULL )
{
char *newline = strchr(filename, '\n'); /* search for newline character */
if ( newline != NULL )
{
*newline = '\0'; /* overwrite trailing newline */
}
printf("filename = \"%s\"\n", filename);
}
filepointer=fopen(filename,"r");
fseek(filepointer, 0, SEEK_END); // seek to end of file
size = ftell(filepointer);
printf("Size=%d\n",size);
fseek(filepointer, 0, SEEK_SET);
int holderarray[size];
for(i=0; i<size; i++)
fscanf(filepointer, "%d", &holderarray[i]);
nrows=holderarray[0];
printf("Number of rows/columns=%d\n",nrows);
if (filepointer == NULL)
{
fprintf(stderr, "Can't open input file in.list!\n");
exit(1);
}
}
Everything works as expected up until this point. I can't visualize how to add the first half of the values to the new 2 dimensional arrays, hopefully you guys can help. Here's my brainstorming in codeblocks.
int matrix1[nrows][nrows];
int matrix2[nrows][nrows];
for (i=1; i<sizeof(holderarray);i++)
{
for (j=0;j<nrows;j++)
{
matrix[i][j]=holderarray[j];
}
for (i=0;i<sizeof(nrows);i++)
{
for (j=0;j<sizeof(nrows);j++)
{
printf("%d",matrix[i][j]);
}
}
return 0;
int
s).Creative use ofscanf()
after reading the number chars (and translating to yourint
matrix size, of course), would make for a fairly straight-forward solution. – WhozCraig Nov 19 '12 at 9:13