【问题标题】:C how to move through 2 dimensional array based on addressC如何根据地址移动二维数组
【发布时间】:2017-01-18 23:49:03
【问题描述】:

我试图弄清楚如何将二维数组作为一维数组循环。由于二维数组会占用连续的内存,有没有办法通过将索引更改 4 个字节来将二维数组寻址为一维数组。我假设一个整数数组。有人可以提供一个例子吗?我尝试了以下方法,但它不起作用:

for (int i = 0; i < 2; i++){
    for (int j = 0;j < 2; j++){
        z[i][j] = count;
        count++;
    }
}

for (int i = 0; i < 4; i++)
    printf("%d\n", z[i]);

【问题讨论】:

  • 只使用第一个子数组...例如。对于int arr[3][3] 索引arr[0] 从arr[0][0] 到arr[0][8]... 或使用int *,例如:int *p = arr[0]; 并使用p[0] ... p[8]
  • 德米特里,你的评论没有任何意义。当 arr[0][8] 被声明为 [3][3] 时,如何访问它?
  • 建议的副本不好;这是使用复杂的方案来访问具有 2 个下标的 2D 数组,而这试图访问具有 1 个下标的 2D 数组(除非我误解了代码)。

标签: c arrays


【解决方案1】:

二维数组可以像这样在一个循环中迭代:

#include <stdio.h>

int main()
{
    int a[2][2], *p;
    a[0][0] = 100;
    a[0][1] = 200;
    a[1][0] = 300;
    a[1][1] = 400;

    p = &a[0][0];

    while(p!=&a[0][4])
        printf("%d\n", *p++);

    return 0;
}

请记住,数组索引只是数组第一个元素的偏移量,因此a[0][3] 和a[1][1] 之间没有真正的区别——它们都指向同一个内存位置。

【讨论】:

  • 这怎么可能是正确的 a[0][3] 和 a[1][1] 持有不同的值。实际上,根据您的示例, a[0][3] 超出范围,而 a[1][1] 存储 400。哦,它们都是 4 个位置偏移。而 int[][] 几乎是一个 *
【解决方案2】:

像这样访问二维数组

int *array;   // note one level of pointer indirection
array = malloc(width * height * sizeof(int));  / allocate buffer somehow

for(y=0;y<height;y++)
  for(x=0;x<width;x++)
    array[y*width+x] = 0; // address the element by calculation

三个维度

  int *array;   // note one level of pointer indirection
  array = malloc(width * height * depth * sizeof(int));  / allocate buffer somehow

 for(z=0;z<depth;z++)
   for(y=0;y<height;y++)
     for(x=0;x<width;x++)
       array[z*width*height + y*width+x] = 0; // address the element by calculation

通常,使用平面缓冲区比使用 C 和 C++ 复杂的多维数组规则更容易。你当然也可以 使用单个索引遍历整个数组。如果你想设置 向上一个二维数组,然后将该数组转换为单个指针,它的行为 同样的方式。

     #define HEIGHT 50
     #define WIDTH 90
     int array2D[HEIGHT][WIDTH}:

     int * array = reinterpret_cast<int *>(array2D): 

【讨论】:

    【解决方案3】:
    #include <stdio.h>
    #include <stdlib.h>
    #include <stdint.h>   
    
    int arr[4][3]={{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
    
    
    void my_fun(int(*a)[],int m,int n)
    {
    
    for(int i=0;i<m*n;i++)
     {
       printf("%d\n",(*a)[i]);
     }
    
    }
    
    int main()
    {
    
      my_fun(arr,3,4);
    
     return 0;
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-04
      • 2020-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多