【发布时间】:2015-02-24 21:48:52
【问题描述】:
我在将文件中的数据存储到我的动态数组中时遇到问题。我知道我现在拥有的东西是不正确的,但它目前就在那里。我有一个文件,它在第一行基本上包含数据行的数量。以下行有两个并排的整数来表示有序对。我想将这两个整数存储到一个结构 point 中,它表示一个有序对。此外,还有一个具有这样一个结构的数组,它位于另一个结构 list 内部,其中包含数组的大小,或当前存储在数组中的数据量和容量,即空间总量在数组中。
我想将这两个整数存储到int 类型的变量中,然后将它们存储到我的数组内部的point 中,该数组位于我的list 结构中。
我对有两个结构感到非常困惑,并且不确定这是否是正确的方法。欢迎任何反馈。
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
typedef struct
{
int x;
int y;
} point;
typedef struct
{
int size;
int capacity;
point *A;
} list;
// Compute the polar angle in radians formed
// by the line segment that runs from p0 to p
double polarAngle(point p, point p0)
{
return atan2(p.y - p0.y, p.x - p0.x);
}
// Determine the turn direction around the corner
// formed by the points a, b, and c. Return a
// positive number for a left turn and negative
// for a right turn.
double direction(point a, point b, point c)
{
return (b.x - a.x)*(c.y - a.y) - (c.x - a.x)*(b.y - a.y);
}
int whereSmallest(point A[], int begin, int end, point p0)
{
point min = A[begin];
int where = begin;
int n;
for (n = begin + 1; n < end; n++)
if (polarAngle(A[n], p0) < polarAngle(min, p0))
{
min = A[n];
where = n;
}
return where;
}
void selectionSort(point A[], int N, point p0)
{
int n, s;
point temp;
for (n = 0; n < N; n++)
{
s = whereSmallest(A, n, N, p0);
temp = A[n];
A[n] = A[s];
A[s] = temp;
}
}
// Remove the last item from the list
void popBack(list *p)
{
int x;
x = p->size - 1;
p->A[x] = p->A[x + 1];
}
// Return the last item from the list
point getLast(list *p)
{
point value;
value = p->A[p->size];
return value;
}
// Return the next to the last item
point getNextToLast(list *p)
{
point value;
value = p->A[p->size - 1];
return value;
}
int main(int argc, const char *argv[])
{
point p0, P;
FILE *input;
list *p;
int N, n, x, y;
/*Assuming that the first piece of data in the array indicates the amount of numbers in the array then we record this number as a reference.*/
N = 0;
input = fopen("points.txt", "r");
fscanf(input, "%d", &N);
/*Now that we have an exact size requirement for our array we can use that information to create a dynamic array.*/
p = (point*)malloc(N*sizeof(point));
if (p == NULL)//As a safety precaution we want to terminate the program in case the dynamic array could not be successfully created.
return -1;
/*Now we want to collect all of the data from our file and store it in our array.*/
for (n = 0; n < N; n++)
{
fscanf(input, "%d %d", &P.x, &P.y);
p->A[n] = P.x;
p->A[n] = P.y;
}
fclose(input);
free(p);
return 0;
}
【问题讨论】:
-
//As a safety precaution we want to terminate the program in case the dynamic array could not be successfully created.非常好的主意,但不要忘记fclose()文件。还有Don't cast the result ofmalloc(). -
该代码能编译吗?
-
@iharob 没必要,C 标准保证在正常退出时为您关闭文件(通过调用
exit()或从 main 返回)。 -
@orlp 当然,但是你自己做会好很多,因为你可以从一个指示分配失败的函数中返回
NULL,如果你在这种情况下忘记这样做,你会在那种情况下也忘了它,所以我相信总是清理所有东西是个好习惯。 -
@iharob 我只转换结果是因为我的导师建议我们这样做,以防学生的编译器不同。