Search code examples
calgorithmstructconceptualmemory-efficient

Can I store generic arrays in structures?


I am facing a problem with storing arrays in structures, which are further written onto a file.

  1. The arrays are square matrices.
  2. The arrays and the size n are stored in a structure. This structure is then stored in a file(binary file).
  3. The size of this array is subject to input from the user during the run time.
  4. Whenever I read the structure from the file in the future, I want to recover all those elements which were saved as they were(I suspect that is why saving the array as int **a has not worked).

The problem is that the size of matrix can be variable and is subject to user's choice(which is, by the way, also stored in the structure and further onto file). I acknowledge that I can take the size of array to be large enough to accommodate any possible value of size, but that would be a wastage of space. Further if I write every element of the array individually then it would be rather a hassle to handle each value individually. Reading a structure is better than reading many values individually. Of course, if I do this:

struct attribs
{
    int a[n][n], b[n][n], n;
}

then it doesn't work. Is there a smarter way around my problem? As for present I take a[][] and b[][] to be of size 20X20 each, while expected value is 4X4 to 9X9, and store the actual value in n so that only that part can be read easily when the structure is read.


Solution

  • When you write the structure to the file, where the lengths are subject to user's preferences, you should write the size first, then the contents of each array. Then to dynamically re-create the matrix, you need only read the size, allocate the appropriate memory, and read the values.

    How you separate matrix a from matrix b is up to you, but your example shows they are the same size. That suggests that after you read n×n integers into a, you can start reading the saved values of b, assuming you didn't write any possible padding bytes that might exist between a and b (write the size, a, and b separately instead of writing the entire structure at once to avoid padding bytes).

    If you cannot alter the format, and the values are all stored together as a jumble of bytes, you must unfortunately read blindly, storing every value. The last sizeof(int) bytes will be the size, again assuming there are no padding bytes.

    If possible, save yourself a lot of trouble and write the size first, followed by matrix a, then matrix b.

    Of course, since the matrix is dynamically sized, perhaps you allocated an array of pointers dynamically first, then an array of ints for each. In that case, unless you looped through each element of a (a[0], a[1], ...), you wrote the pointers to the file instead of the values they pointed to.