I know how to read a file into a 2d array using for loops to direct where you are storing the data in C, but what I am interested in is if you can use one fread() call to do this. That is, can I do something like this:
int A[5][5];
fread(&A, sizeof(int), 25, filePtr);
I am getting seg faults when I tried this so right now so I am wonder if this can be done at all.
EDIT:
Alright, I guess using fread this way isn’t really my problem. My problem is that I have to call fread from within a function and A is defined outside of that function.
func(int size, int ***A)
{
fread(*A, sizeof(int), size*size, filePtr);
}
main
{
int A[n][n];
func(n, &A);
}
So my problem is that my call to fread still seg faults and I HAVE to use a triple pointer for my function prototype. I tried just A (instead of *A) for fun but still got the same seg fault. It looks like I’m just overlooking something with pointers.
My problem was that of contiguous memory. It’s actually very straight forward when you realize that fread is only set up to take single pointers. Therefore it can only take 1-d arrays. However, if your 2-d array is represented in memory contiguously it is analogous to a 1-d array. Therefore, just pass fread a pointer to the first element in your 2-d array, it will start looping through it as if it is a 1-d array and all will be well.
So just make sure your 2-d array is contiguously assigned and you should be fine.
instead of mallocing in a for loop for each row.