Memory space occupied by an array

13,190

Memory occupied by an array can be gotten by using sizeof operator. For example

char array_nr1[40];

printf( "%zu\n", sizeof( array_nr1 ) );

The output will be 40 because sizeof( char ) that is size of the element of the array is guaranteed to be equal to 1

You could write the same for example for array

int array_nr1[10];

But it would be better to calculate the size of array by multiplying sizeof of its element by the numkber of elements.

So this record

sizeof( array_nr1 )

is equivalent to

10 * sizeof( int )

So the question is what is the size of an object of type int? It depends on the implementation. For example sizeof( int ) can be equal to 2 or to 4 or to some other value.

So in your case if sizeof( int ) is equal to 2 then these two arrays

int array_nr1[10];
int array_nr2[10]; 

occupy 2 * ( 10 * sizeof( int ) ) => 40 bytes. It is the same memory volume that is occupied by array

char array_nr1[40];

If sizeof( int ) is equal to 4 then the arrays occupy different amounts of memory.

The same observation is valid for arrays of type float. Usually the size in bytes of an object of type float is equal to 4. So if sizeof( int ) is equal to 2 then these arrays

char array_nr1[10];
int array_nr2[5];
float array_nr3[5];

occuoy the same amount of memory as array

char array_nr1[40];

because

10 * sizeof( char ) + 5 * sizeof( int ) + 5 * sizeof( float ) => 10 * 1 + 5 * 2 + 5 * 4 => 40 bytes.

Share:
13,190
CalinTamaian
Author by

CalinTamaian

Updated on June 14, 2022

Comments

  • CalinTamaian
    CalinTamaian almost 2 years

    This is a basic question, but I couldn't find a definitive answer. Hope someone can shed some light.

    I want to know how much memory space does one array occupy.

    Do multiple arrays of different types but with the same combined byte size occupy the same amount of memory?

    Does an array occupy the same memory space as multiple arrays with the same size combined?

    Some examples:

    (on my system 8051 microcontroller, char = 1 byte; int = 2 bytes ; float = 4 bytes;)

    //case 1
    char array_nr1[40];
    
    //case 2
    char array_nr1[10];
    char array_nr2[10]; 
    char array_nr3[10]; 
    char array_nr4[10]; 
    
    //case 3 
    int array_nr1[10];
    int array_nr2[10]; 
    
    //case 4
    float array_nr1[10];
    
    //case 5 
    char array_nr1[10];
    int array_nr2[5];
    float array_nr3[5];
    

    Do all 5 cases take the same amount of memory (40 bytes)? Is there any other data that is stored on a memory (ex. the array base address)

    Thank you.