Home > Enterprise >  How to reduce the reserved memory that is not currently being used in an array in C?
How to reduce the reserved memory that is not currently being used in an array in C?

Time:11-30

Let's say we reserved 32 bytes for an array in C, but it turns out we are only using 24 bytes, how can I reduce the reserved memory that is not currently in use? Is this even possible?

I am not using malloc, but I could.

This is the working minimal reproducible example:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main() {
 
    FILE *input;
    input = fopen("1.txt", "r");

    int arr[4][300];

    if (input == NULL) {
       printf( "ERROR. Coundn't open the file.\n" ) ;
    } else {
        for (int i = 0; i < 300; i  ) {
            fscanf(input, "%d %d %d %d", &arr[0][i], &arr[1][i],
                    &arr[2][i], &arr[3][i]);
        }
        fclose(input);

        int sze = 0;
        for (int i = 0; i < 300; i  ) {
             for (int j = 0; j < 4; j  ) {
                if (abs(arr[j][i]) >= 1)
                    sze  = log10(abs(arr[j][i]))   1;
                else
                    sze  ;

                if (arr[j][i] < 0)
                   sze  ;
             }
        }
        printf("Size %d kB\n", sze);
    }

    return 0;
}

Clarification: What I need is to reduce the memory used by each element in the array, if possible. Let's say I have the number 45 stored, it doesn't take up all 4 bytes of an int, so I need to reduce the memory allocated to only 1 byte. As I said, I am not currently using malloc, but I could switch to malloc, if there's a way to what I want to.

CodePudding user response:

If you want to reduce the used space for a value, you need to assign it to an object of different type.

In your example, you start with an int that probably uses 4 bytes on your system. Then you store the value "45" in it, which needs just one byte. Types with size of 1 byte are for example int8_t or signed char.

First, you cannot change the type of a variable, once it is defined. You may store it in another variable.

Second, all elements of an array have to be of the same type.

So the answer for the given example is simply "No."

If you want to "compress" the stored values, you need to roll your own type. You can invent some kind of "vector" that stores each value in as few bytes as necessary. You will need to store the size of each value, too. And you will need to implement access function to each vector element. This is not a simple task.

  • Related