The amount of memory occupied by the array

This is the main question, but I could not find a definitive answer. Hope someone can shed some light.

I want to know how much memory space one array occupies.

Do several arrays of different types, but with the same combined byte size, use the same amount of memory?

Is an array used in the same memory space as multiple arrays with the same size?

Some examples:

(on my system, an 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 occupy the same amount of memory (40 bytes)? Is there any other data that is stored in memory (for example, the base address of the array).

Thank.

+4
source share
1 answer

, , sizeof.

char array_nr1[40];

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

40, sizeof( char ), 1

, ,

int array_nr1[10];

, sizeof .

,

sizeof( array_nr1 )

10 * sizeof( int )

, , int? . sizeof (int) 2 4 .

, , sizeof( int ) 2,

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

2 * ( 10 * sizeof( int ) ) = > 40 . ,

char array_nr1[40];

sizeof( int ) 4, .

float. float 4. , sizeof( int ) 2,

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

occuoy ,

char array_nr1[40];

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

+4

All Articles