c - 不确定如何将整数从文件存储到 c 中的结构

标签 c struct segmentation-fault void-pointers

我创建了两个结构来存储值。

struct pair {
    int x_pos;
    int y_pos;
};

struct coordinates_header {
    int length;
    struct pair data[1000];
};

typedef struct coordinates_header coordinates;
coordinates *coords;

然后我尝试使用存储文件中的数据

char line[max_read];
int x, y;
FILE *in_file = fopen(filename, "r");
int i = 0;
coordinates *new = (coordinates *)coords;
while (fgets(line,max_read,in_file) != NULL) {
        sscanf(line,"%d %d", &x, &y);
        new -> data[i].x_pos = x;
        new -> data[i].y_pos = y;
        i++;
    }
new -> length = i;

然后我尝试打印出这些值

int print_struct(void *coords) {
    coordinates *new = (coordinates *)coords;
    for (int i = 0; i < new -> length; i++) {
        printf("%d, %d\n", new->data[i].x_pos, new->data[i].y_pos);
    }
    return 0; 
}

然后我遇到了段错误 我想知道是否有人可以指出错误在哪里。我没有使用 void 的经验,但需要我将要使用的某些函数的结构具有灵 active 。

读取的文件将具有以下形式

100 30
50 200
.. ..

最佳答案

我相信您的代码中存在一些错误:

  • 您应该只声​​明一个结构成员坐标coords,而不是使用坐标 *coords;(它只是一个悬空指针,不指向内存中的任何位置)。
  • 您的代码中不需要 void* 指针。您最好使用坐标 *coords 来访问结构成员坐标 coords 的地址,而不是使用 void *coords 。
  • 您没有检查FILE *in_file的返回值,如果未正确打开,它可能会返回NULL
  • 检查 sscanf() 的结果总是好的,以防万一在一行上找不到两个 xy 坐标.

根据这些建议,您可以像这样编写代码:

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

#define NUMCOORDS 1000
#define MAXREAD 100

typedef struct {
    int x_pos;
    int y_pos;
} coords_t;

typedef struct {
    coords_t coords[NUMCOORDS];
    int length;
} coordinates_t;

void print_struct(coordinates_t *coordinates);

int main(void) {
    coordinates_t coordinates;
    char line[MAXREAD];
    FILE *in_file;
    int i = 0;

    in_file = fopen("coords.txt", "r");
    if (in_file == NULL) {
        fprintf(stderr, "Error reading file.\n");
        exit(EXIT_FAILURE);
    }

    while (fgets(line, MAXREAD, in_file) != NULL) {
        if (sscanf(line, "%d %d", &coordinates.coords[i].x_pos,
                                  &coordinates.coords[i].y_pos) != 2) {

            fprintf(stderr, "two coordinates(x, y) not found.\n");
            exit(EXIT_FAILURE);
        }
        i++;
    }
    coordinates.length = i;

    print_struct(&coordinates);

    fclose(in_file);

    return 0;
}

void print_struct(coordinates_t *coordinates) {
    int i;

    for (i = 0; i < coordinates->length; i++) {
        printf("%d, %d\n", coordinates->coords[i].x_pos, coordinates->coords[i].y_pos);
    }
}

关于c - 不确定如何将整数从文件存储到 c 中的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41646807/

相关文章:

c - 函数中的返回语句从不打印到屏幕

swift - 解析查询结果出错

c - 使用指针而不是数组时出现段错误

c++ - OpenMP 中的本地指针

复杂的通用堆栈

c++ - 在类中初始化静态结构 tm

c - 如何在结构数组中初始化和动态分配一个 int 指针成员?

无法在 Windows 10 上编译 Cairo C 代码

php - 回显Linux发送到Arduino的数据

struct - 在 Julia 中为结构数组创建和赋值