【发布时间】:2014-10-13 07:17:52
【问题描述】:
我需要一些关于我的结构实现数组的想法。这就是我的结构中的内容。我计划使 SHAPES 成为一个数组,因为我将有多个 SHAPES。每个形状将有多个 x 和 y 坐标。因此,我不确定是否应该制作链接列表。开始和结束的目的是我最终将在我的形状正确后运行搜索算法。
struct START
{
int x;
int y;
};
struct END
{
int x;
int y;
};
struct SHAPES
{
int x [100];
int y [100];
int *link;
};
struct DISTANCE
{
int distance_traveled;
int distance_to_finish;
};
我正在阅读这篇文章,想知道在创建结构时是否需要 malloc 或 calloc。如果是,为什么,如果不是,为什么? Malloc 和 calloc 总是让我感到困惑。
How do you make an array of structs in C?
int main(int argc, char *argv[])
{
//Is it better to make these pointers?
struct START start;
struct END end;
struct SHAPES shapes[100];
while(fgets(line, 80, fp) != NULL)
{
//I have a very annoying issue here, I don't know the size of the lines.
//If there are more values I want to increment the x[] and y[] array but NOT the
//shapes array. I can only think of one way to deal with this by putting a bunch of
//variables in the sscanf. I discovered putting sscanf on the next line didn't do what
//I was hoping for.
sscanf(line, "%d%*c %d%*c ", &shapes[i].x[i] , &shapes[i].y[i] );
printf(" line is: %s \n", line);
sscanf(line, "%d%*c %d%*c ", &x1_main , &y1_main );
printf(" line is: %s \n", line);
printf(" shapes[i].x[i] is: %d \n", shapes[i].x[i]);
printf(" shapes[i].y[i] is: %d \n", shapes[i].y[i]);
printf(" x1_main is: %d \n", x1_main);
printf(" y1_main is: %d \n", y1_main);
i++;
memset(line, 0, 80);
}
}
这就是我的文件的样子。添加%*c 似乎可以适当地处理逗号和分号。
10, 4
22, 37
22, 8; 2, 0; 3, 6; 7, 8; 5, 10; 25, 2
1, 2
我从这里得到了这个想法。
【问题讨论】:
-
不清楚为什么
START和END有不同的类型(或者为什么你喜欢大喊大叫;通常,为宏保留所有大写名称,而不是类型 - 标准 @ 987654330@ 和 POSIXDIR *尽管有)。当然,您可以将此称为“位置”,然后您的Shape应该包含一个Position值数组。创建形状的链接列表没有不言而喻的理由。如果您使用 C99 或 C11,您可能会考虑使用灵活的数组成员,但这也可能会让您太难了。 -
要处理一行中未知数量的条目,请考虑How to use
sscanf()in loops? -
我强烈怀疑,当每个形状可以容纳 100 个点时,您在数组中使用 100 个形状是错误的。我认为,您应该先填充一个形状的前 100 个点,然后再移动到数组中的另一个条目。
-
至于
malloc()等:当数组太大而无法在堆栈上分配或者直到运行时才知道它的大小并且任何预分配可能是太小(或需要使用太多空间才合理)。尽可能使用数组;必要时使用列表。数组使您可以轻松访问任何元素,但很难在数组中间删除或添加元素。列表很灵活(很容易添加,也可以从列表中间删除),但与使用数组相比,在列表中查找特定元素通常很慢。 -
@JonathanLeffler 开始和结束的目的是因为我将在正确构建形状后运行搜索算法。我需要 Start 和 End 才能正确运行算法。