繁体   English   中英

如何在C中建立具有可变列长的表(二维数组)?

[英]How to build a table (2D array) with variable column length in C?

是否可以建立具有可变列长的表(二维数组)? 如果可能的话我该怎么做?

这里有代码,但列长是固定的。

#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行的p[i][j] j个元素。

// displaying ith row of length = len

for ( j = 0; j < len; ++j) {
    printf("%d\n" p[i][j]);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM