c - 如何创建一个多维数组,其维度基于 C 中的变量?

标签 c arrays multidimensional-array dynamic

基本上,我希望能够在终端中输入维度 n 并创建相应的 n 维数组。

现在我只能创建一个具有相应 n 维数组大小的一维数组。

最佳答案

不能,数组的维数是类型的一部分,所以需要在编译时知道。您可以做一些简单的数学运算,将您想要的内容映射到一维数组。

例子:

令维度 = 3

  • 宽:4
  • 小时:8
  • 天数:16

代码:

int* data = (int*)malloc(sizeof(int) * w * h * d);
int x = access(1,2,3);  //it will map to location: 1 + 2 * (4) + 3 * (4 * 8)
free(data);


int access(int x, int y, int z){
   return data[x + y * (w) + z * (h * w)];
}

一般的实现可能是这样的

int numDimensions;
printf("Enter number of dimensions:");
scanf("%d", &numDimensions);
int* dimensionSizes = (int*)malloc(sizeof(int) * numDimensions);

//Read each dimension's size
int totalElements = 1;
for(int i = 0; i < numDimensions; ++i){
    printf("Enter size for dimension %d:", i);
    scanf("%d", &dimensionSizes[i]);
    totalElements *= dimensionSizes[i];
}

//allocate 1d array
int* data = (int*) malloc(sizeof(int) * totalElements);

//Read the coordinates you want to store data to
int* position = (int*)malloc(sizeof(int) * numDimensions);
for(int i = 0; i < numDimensions; ++i){
    printf("Enter location in dimension %d:", i);
    scanf("%d", &position[i]);
}

//Read the value you want to store
int value;
printf("Enter value for that position:");
scanf("%d", &value);

//Write the data to the calculated 1d location
data[to1d(position, dimensionSizes, numDimensions)] = value;

int to1d(int* position, int* dimensionSizes, int numDimensions){
    int multiplier = 1;
    int position1d = 0;
    for (int i = 0; i < numDimensions; ++i){
        position1d = position1d + position[i] * multiplier;
        multiplier = multiplier * dimensionSizes[i];
    }
    return position1d;
}

关于c - 如何创建一个多维数组,其维度基于 C 中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54653635/

相关文章:

c - Windows XP 上的 GCC 编译器错误

c - 如何访问 C 结构体中的指针成员?

c - 二叉树遍历导致堆栈溢出

java - 在 JSONArray 中搜索 JSON 元素

python - 在 python 中将 1D 数组插入到 3D 数组网格中

c - 具有静态变量的 C 函数中的单元测试

javascript - 在数组中查找子字符串 - javascript

c++ - 二维数组动态分配C++

c - 访问二维数组一行末尾的元素是 UB 吗?

c# - 将 C++ 二维固定长度 char 数组编码(marshal)为结构成员