C中的数组数组,其中数组的长度不同 [英] Array of arrays in C, where the arrays are of different length
问题描述
我了解您可以轻松制作一个固定长度的矩阵:
I understand that you can easily make a matrix with a fixed length:
double m[][2];
但是,我希望有一个数据结构,它是一个数组,在其中存储长度不同的double类型的数组.我该怎么办?
However, I want to have a datastructure which is an array, where I store arrays of double type which have different lengths. How do I do that?
一个例子是:
arr1 = {1,2,3,4};
arr2 = {1,2};
推荐答案
锯齿状的数组 通常表示为C语言中的指针数组:
Jagged arrays are commonly represented as arrays of pointers to pointers in C:
double arr0[] = {4, 1, 7};
double arr1[] = {1, 2, 3, 4};
double arr2[] = {1, 2};
double *m[] = {arr0, arr1, arr2};
不幸的是,没有标准的语法来定义与指针的外部数组成一直线"的内部数组.
Unfortunately, there is no standard syntax for defining inner arrays "in line" with the outer array of pointers.
请注意,现在无法找到每个内部数组的长度,因此您需要添加某种标记"或单独存储长度:
Note that there is no way to find the length of each inner array now, so you need to add some sort of a "marker", or to store lengths separately:
#define SIZE(arr) (sizeof(arr)/sizeof(arr[0]))
...
size_t len[] = { SIZE(arr0), SIZE(arr1), SIZE(arr2) };
这篇关于C中的数组数组,其中数组的长度不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!