Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to access c 2d array with 1 index

I have the following:

#include <stdio.h>

int main() {

    int a[2][2] = { 0,1,2,3};
    printf("\n%d %d \n%d %d\n",a[0][0],a[0][1],a[1][0],a[1][1]);
    printf("%d %d %d %d\n",*a[0],*a[1],*a[2],*a[3]);

    return 0;
}

which returns:

0 1 
2 3
0 2 0 1491303602

Is there a way to access the 2d array with 1 index? Since the array is held in contiguous memory, shouldn’t we be able to do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

also:

printf("\n%d %d \n%d %d\n",&a[0][0],&a[0][1],&a[1][0],&a[1][1]);
printf("%d %d %d %d\n",a[0],a[1],a[2],a[3]);

produces the following:

1137924528 1137924532 
1137924536 1137924540
1137924528 1137924536 1137924544 1137924552

so why are the memory addresses of the first two elements &a[0][0] = a[0]
and &a[0][1] = a[1] but the last two don’t match?

>Solution :

#include <stdio.h>

int main(void) {

    int a[2][2] = { 0,1,2,3};
    printf("\n%d %d %d %d\n",a[0][0],a[0][1],a[1][0],a[1][1]);
    printf("%d %d %d %d\n",*a[0],*(a[0] + 1), *a[1], *(a[1] + 1));
}

https://godbolt.org/z/3avvnssn5

Result:

0 1 2 3
0 1 2 3
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading