基本上,我希望能够在终端中输入维度 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/