Ex 17 Heap and stack

I don’t understand the way structs are created in this chapter.We create a struct and then write it into a file. email,name,id is created in Address or Database or Connection.

struct Address *addr = &conn->db->rows[id];
conn->db->rows[id] = addr;
struct Database *db = conn->db;

I dont understand exactly what does this line do. It assigns addr to conn. Is the data created twice. Using Address struct and Database struct which is nested in Connection.

There are subtle differences between creating and accessing structs and between a struct and a pointer to a struct.

struct Address *addr = &conn->db->rows[id]

Here you don’t create a struct but look up the memory address of an existing struct in the database and save that memory address in the variable addr: it’s a pointer that you can now use to quickly find the struct.

conn->db->rows[id] = addr;

This assigns (copies) whatever addr is to that slot in the database.

struct Database *db = conn->db;

This is similar to the first snippet. You look up where the db member of your database connection lives in memory and save that location in the pointer called db.

Does this help?
If not, feel free to provide the actual context of those lines and we may be able to help you see what’s going on.

struct address
{
   int pin;
   int stat;
};

struct addr {
   struct address stat1[100];
 };

void create(struct addr *add1)
{
struct address add = {560016,2};
add1->stat1[0] = add;
printf("%d %d\n",add.pin,add.stat);//(outside this function struct add can not be printed)
printf("%d %d\n",add1->stat1->pin,add1->stat1->stat);

}

int main()
{
struct addr *ad = malloc(sizeof(struct addr));    
create(ad);
printf("%d %d\n",add.pin,add.stat);(
printf("%d %d\n",ad->stat1->pin,ad->stat1->stat);
return 0;
}

Okay,I understood that it’s assigning to another struct. In the function create() above we can print the data of struct address add only in that function.Whereas when function is defined,I can print struct ad even outside function which was assigned by struct address add. Are those function in that chapter written in same way as to make us understand about nested functions or is there any other purpose.

I think there’s a misunderstanding when you say:

“In the function create() above we can print the data of struct address add only in that function.”

You can print those addresses anywhere you have the *ad pointer. It’s just in create you’re passing that pointer in to the function so it can modify it. Think of it as an “out parameter” where you’re using a pointer so you can change the value instead of returning a copy.

I also think you might be using confusing variable names that are hiding what’s going on. So you have add, add1, ad, stat1, all of those seem the same. Try giving them meaningful names and it’ll help you sort out what’s going on.

1 Like
A free service run by Zed A. Shaw for learncodethehardway.org.