动态调整结构 - 学习C艰难的历程EX17 [英] Dynamically sized structs - Learn C The Hard Way Ex17

查看:171
本文介绍了动态调整结构 - 学习C艰难的历程EX17的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有在学习C困难的方法练习的麻烦。运动提供了具有固定的大小和行数的简单数据库程序。下面你可以看到,形成了数据库中的结构。

I'm having trouble with an exercise in Learn C The Hard Way. The exercise provides a simple database program which has a fixed size and number of rows. Below you can see the structs that form the database.

#define MAX_DATA 512
#define MAX_ROWS 100

struct Address {
    int id;
    int set;
    char name[MAX_DATA];
    char email[MAX_DATA];
};

struct Database {
    struct Address rows[MAX_ROWS];
};

struct Connection {
    FILE *file;
    struct Database *db;
};

任务是更改code接受MAX_DATA和MAX_ROWS参数它们存储在数据库中的结构,并编写到文件中,从而创建一个可以任意大小的数据库。

我知道如何从用户接受MAX_DATA和MAX_ROWS,作为命令行参数 - 在函数文件中定义的下方。一旦我有这些价值观,我不知道如何将它们存储在数据库结构和写入文件。

I understand how to accept MAX_DATA and MAX_ROWS from the user, as command line arguments - in a function defined lower down in the file. Once I have these values I am not sure how to store them in the database struct and write to a file.

鸭preciate人谁能够提供帮助。你可以在这里找到code的其余部分:的http:// C。学习codethehardway.org /电子书/ ex17.html

Appreciate anyone who is able to help. You can find the rest of the code here: http://c.learncodethehardway.org/book/ex17.html

推荐答案

好吧,我设法最终得到这个节目的工作中,我总结如下。我希望这可以帮助别人还停留在EX17。

Okay I managed to finally get this program working, I've summarized below. I hope this might help someone also stuck on ex17.

首先,我删除了MAX_DATA和MAX_ROWS常数,改变了结构,像这样:

First, I removed the MAX_DATA and MAX_ROWS constants and changed the structs like so:

struct Address {
    int id;
    int set;
    char *name;
    char *email;
};

struct Database {
    int max_data;
    int max_rows;
    struct Address **rows;
};

struct Connection {
    FILE *file;
    struct Database *db;
};

我分配 max_data MAX_ROWS 来在结构中的新变量,并将它们把它们写到文件。

I assign max_data and max_rows to the new variables in the struct and them write them to the file.

conn->db->max_data = max_data;
conn->db->max_rows = max_rows;

int rc = fwrite(&conn->db->max_data, sizeof(int), 1, conn->file);
rc = fwrite(&conn->db->max_rows, sizeof(int), 1, conn->file);

现在我可以运行我的程序和替换 MAX_ROWS &安培; MAX_DATA conn-> DB-GT&; MAX_ROWS &安培; conn-> DB-方式> max_data

Now I can run my program and replace MAX_ROWS & MAX_DATA with conn->db->max_rows & conn->db->max_data.

这篇关于动态调整结构 - 学习C艰难的历程EX17的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆