How does program C get information from an array from within?

I am relatively new to programming, so when someone suggested that creating an array of structures (each containing n attributes of a certain “element”) was faster than creating n attribute arrays, I found that I did not know enough about arrays to argue anyway.

I read this:

how arrays work inside c / c ++

and

Tutorial on the main arrays

But I still don't understand how the C program retrieves a specific value from an array by index.

It seems pretty obvious that the data elements of the array are stored next to the memory and that the name of the array points to the first element.

Are C programs smart enough to do arithmetic based on the data type and index to determine the exact memory address of the target data, or should the program somehow sort through each intermediate piece of data before it arrives (as in the data structure of linked lists)?

More fundamentally, if a program requests a piece of information at its memory address, how does the machine find it?

+3
source share
3 answers

Let's look at a simpler example. Let's say you have an array int test[10]that is stored as follows at address 1000:

1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10

The compiler knows that, for example, int is 4 bytes. The array access formula is as follows:

baseaddr + sizeof (type) * index

- , . :

struct test {
  int i;
  char c;
}

5. - .

, ( ), MMU , , , .

+5

:

C .

, , . ( , ).

+2

, .

, : int A[10];
A .

, A[i], , *(A+i).

, , .

, , , . , .

+1

All Articles