C中的锯齿状阵列(3D)

时间:2011-01-17 07:13:14

标签: c arrays pointers stack jagged-arrays

我怎么能这样做?

double layer1[][3] = {
    {0.1,0.1,0.8},
    {0.1,0.1,0.8},
    {0.1,0.1,0.8},
    {0.1,0.1,0.8}
};
double layer2[][5] = {
    {0.1,0.1,0.1,0.1,0.8}
};
double *upper[] = {layer1, layer2};

我尝试了不同的想法后阅读了以下内容;无济于事。 Do jagged arrays exist in C/C++?

我明白(我希望)

double **upper[] = {layer1, layer2};

类似于我想要的,但不起作用,因为图层不是指针数组。我故意使用C语言。


我正在努力避免这样做(有效)。

double l10[] = {0.1,0.1,0.8};
//l11 etc
double *l1[] = {l10,l11,l12,l13};
double l20[] = {0.1,0.1,0.1,0.1,0.8};
double *l2[] = {l20};

double **both[] = {l1, l2};

3 个答案:

答案 0 :(得分:3)

在现代C中,有一个工具调用复合文字,可以至少部分地实现你想要的东西:

double (*(layer1[])) = {
  (double[]){0.1,0.1,0.8},
  (double[]){0.1,0.1,0.8},
  (double[]){0.1,0.1,0.8},
  (double[]){0.1,0.1,0.8}
};
double (*(layer2[])) = {
    (double[]){0.1,0.1,0.1,0.1,0.8}
};
double (*(*(upper[]))) = {layer1, layer2};

我已将()放入类型中,以显示类型的绑定规则。但请注意,使用这种类型的编程,您必须始终记住数组边界。

编辑:作为(double[]){ 0.0 }的构造称为复合文字,与您在第二个版本中声明的临时数组具有相同的效果。优点是您不必为它们发明命名约定,并且访问这些临时变量的唯一方法是通过更大的数组。也许最好将const放入所有这些中,这样你就不会意外地改变指针:

double (*const(layer1[])) = {
  (double[]){0.1,0.1,0.8},
  (double[]){0.1,0.1,0.8},
  (double[]){0.1,0.1,0.8},
  (double[]){0.1,0.1,0.8}
};
double (*const(layer2[])) = {
    (double[]){0.1,0.1,0.1,0.1,0.8}
};
double (*const(*const(upper[]))) = {layer1, layer2};

这仍然允许您更改内容(所有doubles)但不更改指针。如果您知道doubles本身在整个计划期间没有变化,请将double更改为double const

答案 1 :(得分:1)

struct {
  size_t length;
  size_t stride;
  double *data;
} upper = {
  {
    sizeof(layer1) / sizeof(layer1[0]),
    sizeof(layer1[0]) / sizeof(layer1[0][0]),
    (double *)layer1,
  },
  {
    sizeof(layer2) / sizeof(layer2[0]),
    sizeof(layer2[0]) / sizeof(layer2[0][0]),
    (double *)layer2,
  },
};

int i, j, k;
for (i = 0; i < sizeof(upper) / sizeof(upper[0]); i++) {
  for (j = 0; j < upper[i].length; j++) {
    for (k = 0; i < upper[i].stride; k++)
      printf(" %d" + !k, upper[i].data[upper[i].stride * j + k]);
    printf("\n");
  }
  printf("\n");
}

你必须意识到C中的多维数组只是行主要打包到线性存储中。实际维度仅在编译时由类型所知:它们在运行时无法在数据中找到。

答案 2 :(得分:0)

Layer1和Layer2是指针数组,通过对锯齿状数组的定义。 没有理由

double ** upper[] = {layer1, layer2}

不工作。如果没有,请发布错误消息。

唯一的问题是你的数组会衰减到指针。如果这对您来说是个问题,您需要使用C99并在您已经提到的主题中阅读this post