是否可以构建一个具有可变列长度的表(二维数组)?如果可能的话我该如何做到这一点?
这里我有代码,但列长度是固定的。
#include <stdio.h>
const int CITY = 2; // column number
const int WEEK = 2; // row number
int i,j;
int z=0;
int c[4]={1,2,3,4};
int main()
{
int temperature[CITY][WEEK]; // create temp 2d array of city and weak
for ( i = 0; i < CITY; ++i)
{
for( j = 0; j < WEEK; ++j) {
temperature[i][j]= c[z];
z++;
}
}
printf("\nDisplaying values: \n\n");
for ( i = 0; i < CITY; ++i) {
for(j = 0; j < WEEK; ++j)
{
printf("City %d, Day %d = %d\n", i, j, temperature[i][j]);
}
}
return 0;
}
最佳答案
您可以创建一个指针数组,该数组将指向不同长度的数组。
int *p[row], i;
for(i = 0; i < row; i++) {
p[i] = malloc(len * sizeof(int)); // len is length for row i
}
然后可以通过p[i][j]
访问第i行的第j个元素。
// displaying ith row of length = len
for ( j = 0; j < len; ++j) {
printf("%d\n" p[i][j]);
}
关于c - 如何在C中构建具有可变列长度的表(二维数组)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43851733/