Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Figuring out addresses in C [closed]

I'm trying to learn how to figure out addresses in C. For the code below, assuming it's compiled on a 32-bit little endian machine.

struct {
    int n;
    char c;
} A[10][10];

Say the address of A[0][0] is 1000(decimal), what would the address of A[3][7] be? Any help is appreciated!

like image 839
Joe Crawley Avatar asked Dec 16 '25 23:12

Joe Crawley


2 Answers

C is row-major ordered, which means that the left-most index is computed first. Thus:

&A[3] == 1000 + (3 * 10 * sizeof(your_struct))

To find the column, we just add the remaining index:

&A[3][7] == 1000 + (3 * 10 * sizeof(your_struct)) + (7 * sizeof(your_struct))

Note that this has nothing to do with big-endian vs little-endian architecture. That's just the location of bytes within a word, whereas you want the location of structs within an array.

Also, sizeof(your_struct) isn't guaranteed to be sizeof(n) + sizeof(c) because the compiler could pad your struct.

Lastly, the 32-bit nature of your machine means that the size of the memory-address register is 32 bits. (Or to put it another way, sizeof(void*)==32). It's an indication of how much memory your processor can actually assign an address to. That is a separate issue from the size of data types in C.

like image 157
chrisaycock Avatar answered Dec 19 '25 11:12

chrisaycock


This is not dependent on the C language standard but on the compiler, compiler version and OS you are using/targeting.

The only way to get a result for your specific case will be to manually test.

like image 33
0x90 Avatar answered Dec 19 '25 13:12

0x90



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!