简体   繁体   English

如何将一维数组作为二维数组访问?

[英]How to access 1D array as 2D array?

I'm trying to access 1D array as 2D array. 我正在尝试将1D数组作为2D数组访问。 But it falls into Segv. 但是它属于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. 反之亦然(将2D数组作为1D数组访问)情况可以通过类型转换简单地处理。下面是代码段,这很好用。

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: 您想使用reinterpret_cast获得对存储在数组中的数据的引用:

#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 例如: https//ideone.com/thc55R

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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