I'm having some trouble wrapping my head around pointer assignments in C. The asterisk character appears in many different locations and I don't understand why I would choose to use one way over the other.
Specifically in the code below:
why would I choose:
conn->db->rows = (struct Address**)malloc(sizeof(struct Address *) * conn->db->MAX_ROWS);
over:
conn->db->rows = (struct **Address)malloc(sizeof(struct Address *) * conn->db->MAX_ROWS);
and within sizeof, what does the asterisk indicate?
This is the origin of the code above. Not the entire program.
struct Address {
int id;
int set;
char *name;
char *email;
};
struct Database {
int MAX_DATA;
int MAX_ROWS;
struct Address **rows; // USE ARRAY OF POINTERS
};
struct Connection {
FILE *file;
struct Database *db;
};
void die(const char *message) {
if(errno) {
perror(message);
} else {
printf("ERROR: %s\n", message);
}
exit(1);
}
void Address_print(struct Address *addr) {
printf("%d %s %s\n", addr->id, addr->name, addr->email);
}
void Database_load(struct Connection *conn) {
size_t i=0;
// Each database will have two `int` values. read
// those first.
assert(conn->db && conn->file);
if (!(conn->db && conn->file))
die("Database load : Invalid Connection info");
if (fread(&conn->db->MAX_DATA, sizeof(conn->db->MAX_DATA), 1, conn->file) != 1)
die("Database load : Couldn't read MAX_DATA");
if (fread(&conn->db->MAX_ROWS, sizeof(conn->db->MAX_ROWS), 1, conn->file) != 1)
die("Database load : Couldn't read MAX_ROWS");
conn->db->rows = (struct Address**)malloc(sizeof(struct Address *) * conn->db->MAX_ROWS);
assert(conn->db->rows);
if (!(conn->db->rows)) {
die("Database_load : Could not MAX_ROWS Address structures");
}