I need to pass in a 2D area (a matrix) from the command line through a txt file that looks like this:
0 0 0 0 0
0 1 1 0 0
0 0 1 0 0
0 0 1 0 0
0 0 0 0 0
I'm using C and need to have it in row-major order, so I'm trying to do this:
int matrix[][] = argv[2]; // it is the second command line argument passed
This isn't working, is it because it needs to be a 1-dimensional array? Am I only allowed to use a regular 1D array for row-major ordering? The error I'm getting is "array type has incomplete element type 'int[]' "
I'm trying to do this:
int matrix[][] = argv[2]
This isn't working,
because this is invalid, out of the missing ';' :
Considering argv[2] is the pathname of the file containing the 5x5 matrix the declaration of the matrix can be :
int matrix[5][5];
and you need to read the values in the file to set the matrix's content, you cannot directly map the txt file to matrix
Example :
#include <stdio.h>
int main(int argc, char ** argv)
{
FILE * fp;
if (argc < 3) {
fprintf(stderr, "usage: %s ?? <file>\n", *argv);
return -1;
}
else if ((fp = fopen(argv[2], "r")) == NULL) {
perror("cannot open file");
return -1;
}
else {
int matrix[5][5];
int i, j;
for (i = 0; i != 5; ++i) {
for (j = 0; j != 5; ++j) {
if (fscanf(fp, "%d", &matrix[i][j]) != 1) {
fprintf(stderr, "invalid file for [%d][%d]\n", i, j);
return -1;
}
}
}
fclose(fp);
/* debug */
for (i = 0; i != 5; ++i) {
for (j = 0; j != 5; ++j)
printf("%d ", matrix[i][j]);
putchar('\n');
}
putchar('\n');
/* you can also use it as a 1D array */
for (i = 0; i != 25; ++i) {
printf("%d ", ((int *) matrix)[i]);
if (i%5 == 4)
putchar('\n');
}
return 0;
}
}
Compilation and execution:
pi@raspberrypi:/tmp $ gcc -Wall a.c
pi@raspberrypi:/tmp $ cat f
0 0 0 0 0
0 1 1 0 0
0 0 1 0 0
0 0 1 0 0
0 0 0 0 0
pi@raspberrypi:/tmp $ ./a.out whatever f
0 0 0 0 0
0 1 1 0 0
0 0 1 0 0
0 0 1 0 0
0 0 0 0 0
0 0 0 0 0
0 1 1 0 0
0 0 1 0 0
0 0 1 0 0
0 0 0 0 0
pi@raspberrypi:/tmp $