Hi! I've been looking for working code example that uses 2d arrays with fwrite and fread but haven't found any. So I tried to realize it myself but I cannot get it work. The goal is to make 2d array according to the given size, for example 10x10 and then to write these values into file and afterwards to read these values by using fread. I don't know if save_table function works correctly, because get_table_size returns 0 although it should return 10 because test program makes 10x10 table. Any ideas?
Code:int multiply(int x, int y) { return x*y; } int add(int x, int y) { return x+y; } int ** create_table(int size, int (* oper) (int, int)) { int x; int y; int **2darray; 2darray = malloc (size*sizeof(int*)); for(x = 0; x < size; x++) { 2darray[x] = (int*)malloc(sizeof(int)*size); for(y=0;y<size;y++) { 2darray[x][y]=(* oper)(x,y); } } return 2darray; } int save_table(FILE * fp, int ** table, int size) { int x=0; if(fp==NULL) { return 0; } else { for(x;x < size;x++) fwrite(table[x],sizeof(int),size,fp); } return 1; } int get_table_size(FILE *file) { int nitems; if(file==NULL) return 1 fread(&nitems,sizeof(int),1,file); return nitems; }



LinkBack URL
About LinkBacks



