I have this part of code:
for(i = 0; i < matrix->y; i++)
{
printf("3.%i - %i %i\n", i, matrix->y, matrix->x);//write correct "3.0 - 3 4"
for(j = 0; j < matrix->x; j++)
{
printf("N - %i %i\n", matrix->y, matrix->x);//never write anything
fscanf(input, "%i", &grid[i][j]);
}
printf("3.%i - %i %i\n", i, matrix->y, matrix->x);//write wrong "3.0 - 3 0"
}
first printf outputs y=3 and x=4, but it never goes inside loop, it never reach the second printf inside for-loop. When I write the same printf from the first line after for-loop, it tels me y=3 and x=0.
Where I have done mistake.
Thanks.
Edit
Code is writen as it is. No lines skipped.
Matrix definition
typedef struct matrix
{
int x;
int y;
int ** grid;
} Matrix;
i and j is defined by
int i, j;
Whole function
Matrix * loadMatrix(char * filename)
{
Matrix * matrix;
FILE * input;
input = fopen(filename, "r");
if (input == NULL)
printError (ERR_READFILE);
else
{
fscanf(input, "%i", &(matrix->y));
fscanf(input, "%i", &(matrix->x));
int i, j;
int grid[matrix->y][matrix->x];
matrix->grid = grid;
printf("2 - %i %i\n", matrix->y, matrix->x);
for(i = 0; i < matrix->y; i++)
{
printf("3.%i - %i %i\n", i, matrix->y, matrix->x);
for(j = 0; j < matrix->x; j++)
{
printf("N - %i %i\n", matrix->y, matrix->x);
fscanf(input, "%i", &grid[i][j]);
}
printf("3.%i - %i %i\n", i, matrix->y, matrix->x);
fclose(input);
}
return matrix;
}
Your program’s behavior is undefined because you’re not allocating storage for
matrix. So anything could happen.Add this somewhere after you have declared
matrix(just before thefscanflines seems optimal):and change the line where you declare
matrixto:(otherwise you’ll return garbage if the
fopenfails.)Second problem is that you’re then also failing to allocate proper storage for
matrix->grid. You can’t keep a pointer to a local variable after the function has returned.You’ll need to create that storage with
mallocorcalloctoo. See this question: How do I work with dynamic mutli-dimensional arrays in C for an example of how to do that.You’ll also need to take care to
freeboth of those once you’re finished using them.Don’t forget to
#include <stdlib.h>, which is required formallocandfree.