Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically sized structs - Learn C The Hard Way Ex17

Tags:

c

database

struct

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;
};

the task is to change code to accept parameters for MAX_DATA and MAX_ROWS store them in the database struct, and write that to the file, thus creating a database that can be arbitrarily sized.

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.

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

like image 918
Tom Kadwill Avatar asked Jan 21 '14 21:01

Tom Kadwill


1 Answers

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

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;
};

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);

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

like image 198
Tom Kadwill Avatar answered Sep 28 '22 07:09

Tom Kadwill