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

标签 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行的第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/

相关文章:

c - BlueZ D-Bus C,应用程序 BLE

c - 使用 just while(x)

c - Strchr 和 strncpy 误用

c - fprintf 没有打印到文件

c - 我有一个 C 程序需要一年中的某一天,但我遇到了麻烦

c - 如何配置 git 以忽略文件?

c - 在 C 中将一个函数内联到另一个内联函数中

c - 获取错误-C编程

c - 如何让用户创建一个函数? [ 图书馆 ? ]

c - 如何使用 clock_gettime