Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the address of an index in an array in C

Given the definition of an array in C: int a[2][3][4][5], and the address of a[0][0][0][0] is 1000 what is the address of a[1][1][1][1], assuming an int occupies 4 bytes.

I got:

(3*4*5 * 4bytes) + (4*5 * 4bytes) + (5* 4bytes) + 4bytes = 344

344 + 1000 = 1344 Location of a[1][1][1][1]

but I have no idea if I'm right. But my math seemed sound to me.

like image 625
Schwarz Avatar asked Nov 13 '14 01:11

Schwarz


1 Answers

Just print the adress of the variable any you will see it!:

#include <stdio.h>  

int main() {

    int a[2][3][4][5];

    printf ("Size of int %d\n", sizeof(int));

    printf("Adress of the frist element \t%p\n", &a[0][0][0][0]);
    printf("Adress of x element \t\t%p\n", &a[1][1][1][1]);

    printf ("In decimal: \t\t\t%d\n", &(a[0][0][0][0]));
    printf ("In decimal: \t\t\t%d\n", &(a[1][1][1][1]));

    printf("Difference between the adresses %d", (char *)&a[1][1][1][1] - (char *)&a[0][0][0][0]);




    return 0;

}

After that you can check if you where right!

And as you see your right! it's 334

like image 55
Rizier123 Avatar answered Sep 19 '22 16:09

Rizier123