如何初始化在C 3D连续数组 [英] How to initialize a 3D contiguous array in C

查看:92
本文介绍了如何初始化在C 3D连续数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何做一个potentioal非连续数组中的下列方式:

  INT的main(){
  INT ***阵列=(INT ***)的malloc(3 * sizeof的(INT **));
  INT I,J;  对于(I = 0; I&下; 3;我++){
    //指定数组[我],而不是*数组[I](这将取消引用一个未初始化的指针)
    数组[我] =(INT **)的malloc(3 * sizeof的为(int *));
    为(J = 0; J&下; 3; J ++){
      数组[I] [J] =(INT *)malloc的(3 * sizeof的(INT));
    }
  }  阵列[1] [2] [1] = 10;  返回0;
}

与上面的code时,阵列[0] [j]的块可以是不连续的。为了获得连续的,我觉得我们需要以这种方式的malloc

 为int *阵列=(INT *)malloc的(3 * 3 * 3 * sizeof的(INT));
INT ** Y =(INT **)的malloc(3 * 3 *的sizeof(中间体**));
INT *** X =(INT ***)的malloc(3 *的sizeof(中间体***));  对于(I = 0; I&下; 3;我+ +)
    {
      瓦尔斯=丘壑+ I * M * N;
      X [i] =&放大器;丘壑;
      为(J = 0; J&下; 3; J ++)
    {
    X [I] [J] =丘壑+ J * N;
    }
    }

不过,我troulbe与地址分配。我不是一个C程序员,任何人都可以纠正我的错吗?在此先感谢...


解决方案

  INT *** X =(INT ***)的malloc(3 * sizeof的(INT ***)) ;

  INT *** X =(INT ***)的malloc(3 * sizeof的(INT **));

现在的初始化可以是:

 为(i = 0;我3;;我++)
  {
    X [i] = Y + 3 *我;
    为(J = 0; J&下; 3; J ++)
    {
      X [I] [J] =阵列+ I * 3 * 3 + J * 3;
    }
  }

X [0] x的第一个元素[1] 第四,等等。
X [0] [0] = Y [0] 来的第一个的数组 X [0] [1] = Y [1] 来的第四阵列

I know how to do a potentioal non-contiguous array in the following way:

int main () {
  int ***array = (int***)malloc(3*sizeof(int**));
  int i, j;

  for (i = 0; i < 3; i++) {
    // Assign to array[i], not *array[i] (that would dereference an uninitialized pointer)
    array[i] = (int**)malloc(3*sizeof(int*));
    for (j = 0; j < 3; j++) {
      array[i][j] = (int*)malloc(3*sizeof(int));
    }
  }

  array[1][2][1] = 10;

  return 0;
}

with the code above, the array[0][j] blocks can be not contiguous. To get contiguous, I feel that we need to malloc in this way

int* array = (int*)malloc(3*3*3*sizeof(int));
int** y = (int**)malloc(3*3*sizeof(int**));
int*** x = (int***)malloc(3*sizeof(int***));

  for(i = 0; i < 3; i++)
    {
      vals = vals + i*m*n;
      x[i] = &vals;
      for(j = 0; j < 3; j++)
    {
    x[i][j] = vals + j * n;
    }
    }

However, I got troulbe with address assignment. I am not a c programmer, can anyone correct my fault? Thanks in advance...

解决方案

int*** x = (int***)malloc(3*sizeof(int***));

should be

int*** x = (int***)malloc(3*sizeof(int**));

Now initialization can be :

  for(i = 0; i < 3; i++)
  {
    x[i] = y + 3*i;
    for(j = 0; j < 3; j++)
    {
      x[i][j] = array + i*3*3 + j*3;
    }
  }

So that x[0] points to the first element of y, x[1] to the fourth, etc. And x[0][0]=y[0] to the first of array, x[0][1]=y[1] to the fourth of array, etc.

这篇关于如何初始化在C 3D连续数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆