Typedef中的动态2D数组 [英] Dynamic 2D array in typedef

查看:94
本文介绍了Typedef中的动态2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使它正常工作?我不确定客户将被分配给多少张发票并希望保持动态.请帮忙.

How do I get this to work? I am not sure how many invoices a customer will be assigned to and want to leave it dynamic. Please help.

#include <stdio.h>
#include <stdlib.h>

typedef struct _cust{
    int id;
    int invoices[][2];
} cust;

cust account[] = {
    {1,{10,100}},
    {2,{{10,100},{20,200}}},
    {3,{{10,100},{20,200},{30,300}}}
};

int main(void) {
    printf("%d\n", account[0].invoices[0][0]);
    printf("%d\n", account[1].invoices[1][0]);
    printf("%d\n", account[2].invoices[2][0]);
    return 0;
    }

运行此代码时,出现以下错误...

When I run this code I get following error ...

error: initialization of flexible array member in a nested context

如果我填写一个类似int发票[3] [2]的代码,代码运行正常.

If I give fill in a number something like this int invoices[3][2], the code runs fine.

推荐答案

指向具有两个元素的数组的指针应如下所示:

A pointer to an array with two elements would look like this:

int (*array)[2];

,但先使用typedef可能会更容易:

but it would perhaps be easier for you to use a typedef first:

typedef int pair[2];
.
.
pair * array;

,您可以随时随地为这种野兽分配一大块.如果您使用的是C99(或更高版本)兼容的编译器,则该内容应为

and you can allocate a large chunk to such a beast just in on go. If you have a C99 (or upwards) compatible compiler this would read like

array = malloc(sizeof(pair[n]));

这篇关于Typedef中的动态2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆