Understanding Pointers and Malloc

I am currently learning C, and I am struggling to wrap my head around pointers and the malloc () function.

So, in my example book there is the following function:

island* create(char *name) {
   island *i = malloc(sizeof(island)); 
   i->name = strdup(name);
   i->opens = "09:00";
   i->closes = "17:00";
   i->next = NULL;
   return i; 
}

Then it is called like this:

char name[80];
fgets(name, 80, stdin);
island *p_island0 = create(name);

This code example is hard to understand:

  • What happens to a variable iupon assignment malloc(sizeof(island));, is it just that it temporarily stores a reference to the new memory space allocated in HEAP?

  • After island *p_island0 = create(name);, in the end, what is stored in p_island0? The address created malloc()or created by another pointer, and the value of the previous variable icopied to p_island0on ... STACK?

+4
source share
4

1. malloc (sizeof (island)), , HEAP?

i , malloc(). . , ( free()), , , , .

FWIW, , malloc(), NULL, UB malloc().

2. *p_island0 = create(name);, , p_island0? , malloc() , i, p_island0?

, malloc().

+1

return i; , i, p_island0 , i . , free . , , , malloc.

, , C, , . , , CPU.

+1
  • malloc , void *, , ( ) i.
  • , malloc, p_island0. * , malloc, , , "free" .
+1

island, , .

create (char * name)

island *i = malloc(sizeof(island));

, i. i . .

( ), i, p_island0.

0

All Articles