简体   繁体   中英

How to access 1D array as 2D array?

I'm trying to access 1D array as 2D array. But it falls into Segv. Below is snippet the i had written. Can anyone please take a look into this?

void printarray(int **a){


    printf("#####2D access... \n");
    for(int i=0;i<2;i++){
        for(int j=0;j<2;j++){

            printf("## %u-->%d \n", &a[i][j],a[i][j]);
        }
        }

}

int main(){
    int a[4] = {10,20,30,40};
    printf("%u %u %u \n", &a, a, &a[0]);
    printf("%u %u %u %u \n", &a[0], &a[1], &a[2], &a[3], &a[4]);
    printarray((int **)a);
    return 0;
}

And vice-versa(Accessing 2D array as 1D array) situation is simply handled by type casting.Below is the snippet and this works fine.

void printarray(int *a){
    printf("#####1D access... \n");
    for(int i=0;i<4;i++){
        printf("## %u-->%d \n", &a[i],a[i]);
    }
}

int main(){
    int a[2][2] = {
        {10,20},{30,40}
    };
    printf("%u %u %u %u \n", &a, a, a[0], &a[0]);
    printf("%u %u \n", a[0], &a[0]);
    printf("%u %u \n", a[1], &a[1]);

    printarray((int *)a);
    return 0;
}

thanks, Hari

You want to use reinterpret_cast to get a reference to the data stored in your array:

#include <iostream>

void printarray(int a[2][2])
{
    printf("#####2D access... \n");
    for (int i = 0; i<2; i++)
    {
        for (int j = 0; j<2; j++)
        {

            printf("## %p-->%d \n", &a[i][j], a[i][j]);
        }
    }
}

void printarray(int b[4])
{
    printf("#####1D access... \n");
    for (int i = 0; i<4; i++)
    {
        printf("## %p-->%d \n", &b[i], b[i]);
    }
}

int main()
{
    int a[4] = { 10,20,30,40 };
    int(&arr)[2][2] = reinterpret_cast<int(&)[2][2]>(a);
    printarray(arr);

    int b[2][2] = {{ 10,20 },{ 30,40 }};
    int(&brr)[4] = reinterpret_cast<int(&)[4]>(b);
    printarray(brr);

    return 0;
}

Example: https://ideone.com/thc55R

#####2D access... 
## 0x7fff708c4a90-->10 
## 0x7fff708c4a94-->20 
## 0x7fff708c4a98-->30 
## 0x7fff708c4a9c-->40 
#####1D access... 
## 0x7fff708c4aa0-->10 
## 0x7fff708c4aa4-->20 
## 0x7fff708c4aa8-->30 
## 0x7fff708c4aac-->40 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM