I want to dynamicly construct a matrix in C from a text document using a function. I ran into problems when making the matrix using calloc and probably when giving the values to the matrice elements, and I couldn't find anything. I can handle a vector.
Code here:
#include <stdio.h>
#include <stdlib.h>
void beolvas_ellista(int *, int *, int *, int *, int ***, char *);
int main()
{
int ir, suly, csom, el, i, **ellista;
//The following commented code works
/*FILE * f;
f=fopen("be.txt","r");
fscanf(f,"%d",&ir);
fscanf(f,"%d",&suly);
fscanf(f,"%d",&csom);
fscanf(f,"%d",&el);
ellista=(int **)calloc(2,sizeof(int *));
for(i=0;i<el;++i)
{
ellista[i]=(int *)calloc(el,sizeof(int));
}
i=0;
while(!feof(f))
{
fscanf(f,"%d",&ellista[0][i]);
fscanf(f,"%d",&ellista[1][i]);
++i;
}
for(i=0;i<el;++i)
printf("%d %d\n",ellista[0][i],ellista[1][i]);
fclose(f);*/
beolvas_ellista(&ir, &suly, &csom, &el, &ellista, "be.txt");
for(i=0;i<el;++i)
printf("%d %d\n",ellista[0][i],ellista[1][i]);
return 0;
}
void beolvas_ellista(int *ir, int *suly, int *csom, int *el, int ***ellista, char *allomany)
{
int i;
FILE * f;
f=fopen(allomany,"r");
fscanf(f,"%d",ir);
fscanf(f,"%d",suly);
fscanf(f,"%d",csom);
fscanf(f,"%d",el);
*ellista=(int **)calloc(2,sizeof(int *));
for(i=0;i<*el;++i)
{
*ellista[i]=(int *)calloc(*el,sizeof(int));
}
i=0;
while(!feof(f))
{
fscanf(f,"%d",ellista[0][i]);
fscanf(f,"%d",ellista[1][i]);
++i;
}
fclose(f);
}
Here is the text file:
be.txt
0 0
7 8
1 2
1 3
2 3
3 4
4 5
4 6
5 7
6 7
Also here is the code that I used to gather information:
void beolvas(int*pn, int**pa, char*allomany)
{
int i;FILE*f;
f=fopen(allomany,"r");
fscanf(f,"%d",pn);
*pa=(int*)malloc((*pn)*sizeof(int));
for(i=0; i<*pn; i++)
fscanf(f,"%d",(*pa)+i);
fclose(f);
}
main()
{
int n, *a;
beolvas(&n, &a, "be.txt");
...
}