gpt4 book ai didi

c - C 中半已知输入的指针与数组

转载 作者:太空宇宙 更新时间:2023-11-04 08:02:40 25 4
gpt4 key购买 nike

假设我有一个结构如下(这是在 C 中):

typedef struct Cage {
int cage_size;
int sum;
int** elements;
} Cage;

在我的输入文件中,我的输入是这样读入的:

size a
sum b
x y value
x y value
...

size a
...

其中 a、b、x、y 和 value 都是整数。 a对应cage_sizeb对应sumelements为有序数组作为 {x, y, value, x, y, value ...}。我有一个包含所有 cage 结构的双指针,因为我不知道编译时结构的数量(或 x y value 元组的数量)。

我的问题是:我有未知数量的 x y value 元组,但我知道每个元组始终有三个输入。如何解析元组?像我现在那样存储它们(在双指针中)是否有意义?例如:

int* elements[3]; //would this be a good choice? Is this even legal?

int** elements; //current set-up, but having pointers like this isn't great and
//I suspect I can do better

int* elements; //this might be easiest to use once I have it,
//but how would I allocate the memory when parsing the inputs?
//Maybe I could parse all the lines and store them into a buffer first?

我正在寻找一个好的解决方案,而不是快速修复。我正在努力了解 C 和有效的 IO/内存分配。

最佳答案

它们都有效。最好的解决方案不能从一个小例子中确定。这完全取决于您以后将如何使用这些数据。

关于如何解析元组,一种方法是先malloc 一 block 内存,然后在必要时使用realloc。另一种选择是读取文件,直到找到第一个非三元组,然后回溯。

第一个选项的伪:

size = 1
tuples = malloc(size)
while(nextLine is a tuple)
size++
tuples = realloc(size)
tuples[i]=nextLine

第二个选项的伪:

size=0
while(nextLine is a tuple)
size++
backtrack
tuples=malloc(size)

关于c - C 中半已知输入的指针与数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45024653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com