使用C中的结构将数据存储到动态数组中

时间:2015-02-24 21:48:52

标签: c arrays file struct

我在将数据从文件存储到动态数组时遇到问题。我知道我现在所拥有的是不正确的,但它现在就在那里。我有一个文件,在第一行基本上包含数据行。以下行并排有两个整数来表示有序对。我想将这两个整数存储到一个结构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;
}

2 个答案:

答案 0 :(得分:2)

首先,您的代码无法编译,因为

p->A[n] = P.x;
p->A[n] = P.y;

错了,应该是

p->A[n].x = P.x;
p->A[n].y = P.y;

因为A的类型为point,您应该访问结构的成员以便为它们赋值。

但这只是问题的开始,你没有为A指针分配空间,所以这不起作用。

  1. 您需要为类型为list的实例分配空间,这样做

    p = malloc(sizeof(*p));
    
  2. 然后你需要初始化p的成员

    p->values   = malloc(N * sizeof(point));
    p->capacity = N;
    p->size     = 0;
    

    如您所见,已为values成员分配了空间。

  3. 检查fscanf()以确保数据完整性并避免未定义的行为,如果fscanf()失败,您将永远不会知道您的代码,并且您可能会访问导致未定义行为的未初始化变量。

  4. 从两个int变量中捕获从文件中扫描的值,只有在读取的地方才能将它们复制到数组中

    for (n = 0 ; ((n < N) && (fscanf(input, "%d%d", &x, &y) == 2)) ; n++)
    /* check that the values were read from the file _______^ */
    {
        /* store them in the array */
        p->values[n].x = x;
        p->values[n].y = y;
        p->size       += 1;
    }
    
  5. 检查文件是否已打开。

  6. 我建议使用以下代码

    #include <stdio.h>
    #include <math.h>
    #include <stdlib.h>
    
    typedef struct
    {
        int x;
        int y;
    } point;
    
    typedef struct
    {
        int size;
        int capacity;
        point *values;
    } 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 values[], int begin, int end, point p0)
    {
        point min = values[begin];
        int where = begin;
        int n;
        for (n = begin + 1; n < end; n++)
            if (polarAngle(values[n], p0) < polarAngle(min, p0))
            {
                min = values[n];
                where = n;
            }
        return where;
    }
    void selectionSort(point values[], int N, point p0)
    {
        int n, s;
        point temp;
        for (n = 0; n < N; n++)
        {
            s         = whereSmallest(values, n, N, p0);
            temp      = values[n];
            values[n] = values[s];
            values[s] = temp;
        }
    }
    
    // Remove the last item from the list
    void popBack(list *p)
    {
        int x;
        x = p->size - 1;
        p->values[x] = p->values[x + 1];
    }
    
    // Return the last item from the list
    point getLast(list *p)
    {
        point value;
        value = p->values[p->size];
        return value;
    }
    
    // Return the next to the last item
    point getNextToLast(list *p)
    {
        point value;
        value = p->values[p->size - 1];
        return value;
    }
    
    int main(int argc, const char *argv[])
    {
        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");
        if (input == NULL)
            return -1;
        if (fscanf(input, "%d", &N) != 1)
        {
            fclose(input);
            return -1;
        }
    
        p = malloc(sizeof(*p));
        if (p == NULL)
            return -1;
    
        /*Now that we have an exact size requirement for our array we can use that information to create a dynamic array.*/
        p->values   = malloc(N * sizeof(point));
        p->capacity = N;
        p->size     = 0;
        if (p->values == NULL)//As a safety precaution we want to terminate the program in case the dynamic array could not be successfully created.
        {
            free(p);
            fclose(input);
    
            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) && (fscanf(input, "%d%d", &x, &y) == 2)) ; n++)
        {
            p->values[n].x = x;
            p->values[n].y = y;
            p->size       += 1;
        }
        fclose(input);
    
        free(p->values);
        free(p);
        return 0;
    }
    

    正如您所看到的,您可以对代码进行另一项改进,但它并不太重要,但它会避免使用不必要的Nn变量。

    注意:在使用某个功能之前,请尝试仔细阅读它的文档,以防止出现各种意外结果,例如fscanf(),这将有助于您更多地了解我的修复程序。< / p>

答案 1 :(得分:1)

变量p应为list p

点数组分配为p.A = (point*)malloc(N*sizeof(point));

在填充循环中,由于A [n]是一个点,你不能将它分配给int P.x或P.y.您可以直接将值放入A [n]点,如下所示:

for (n = 0; n < N; n++)
{
    fscanf(input, "%d %d", &(p.A[n].x), &(p.A[N].y));
}

列表的大小和容量应该在成功的内存分配后立即初始化:p.capacity = N;和填充数组后的p.capacity = n;

最后,您应该拨打free(p.A)而不是free(p)