My question is a simple one...I have the following structs declared:
struct Address {
int id;
int set;
char *name;
char *email;
};
struct Database {
struct Address rows[512];
};
struct Connection {
FILE *file;
struct Database *db;
};
Now having that clear, I initialize my "Database" inside my "Connection" with some dummy Addresses. I later take this database and save it into the file inside my "Connection" struct with:
void Database_write(struct Connection *conn){
rewind(conn->file);
int rc = fwrite(conn->db, sizeof(struct Database), 1, conn->file);
if(rc != 1){
die("Failed to write database.\n",conn);
}
rc = fflush(conn->file);
if(rc == -1){
die("Cannot flush database.\n",conn);
}
Everything works great when I have a predetermined number of rows inside my "Database" struct for my Addresses i.e. 512. But, what if I want to make the number of rows dynamically? As in maybe as a param passed to a function? I have tried using the following...
struct Database {
struct Address *rows;
};
And allocating space to this pointer with:
conn->db->rows = (struct Address*) malloc(sizeof(struct Address)*max_rows);
With max_rows being a param passed to a function...But, now the problem is that when I go and try to save this to the file inside my "Connection" struct I just save the pointer "struct Address *rows;" and not the data with the space allocated to it. Any suggestions as to how to save this allocated space or have a predetermined array inside a struct and then grow it dynamically?
Thanks in advance!
malloc()tostruct Address *? or you just do it because you saw it somewhere else? I am asking this because it would be a lot different if you MUST cast, it would be a whole different language. Also,conn->db->rowsmight dereference aNULLpointer if you are not careful. And what isdie()?, it makes the code look like it's PHP, and it's PHP so, it's PHP.