0

can you help me explain this code?

code link below: https://code.sololearn.com/ca28a10a170A #include <stdio.h> #include <stdlib.h> typedef struct { int *elements; int size; int cap; } dyn_array; int main() { dyn_array arr; int i; /* initialize array */ arr.size = 0; arr.elements = calloc(1, sizeof(*arr.elements)); arr.cap = 1; /* room for 1 element */ /* expand by 5 more elements */ arr.elements = realloc(arr.elements, (5 + arr.cap)*sizeof(*arr.elements)); if (arr.elements != NULL) arr.cap += 5; /* increase capacity */ /* add an element and increase size */ if (arr.size < arr.cap) { arr.elements[arr.size] = 50; /* add element to array */ arr.size++; } else printf("Need to expand array."); /* display array elements */ for (i = 0; i < arr.cap; i++) printf("Element %d: %d\n", i, arr.elements[ i ]); return 0; }

6th Apr 2021, 2:59 PM
RAJESH
6 Respostas
+ 2
the /*expand by 5 more elements/* and /*add an element and increase size*/ this 2 section
6th Apr 2021, 3:18 PM
RAJESH
+ 2
Let's begin by understanding calloc and realloc. http://www.cplusplus.com/reference/cstdlib/calloc/ http://www.cplusplus.com/reference/cstdlib/realloc/ I'm not sure what to explain for now, the code is pretty straight forward. If you still have doubt after reading the references, then you're welcome to ask further.
6th Apr 2021, 3:27 PM
Ipang
+ 2
Ipang thanks 🙌
6th Apr 2021, 3:29 PM
RAJESH
+ 2
1.In this line, arr.elements = realloc(arr.elements, (5 + arr.cap)*sizeof(*arr.elements)); here realloc re allocates the memory of arr.element.the value of arr.cap is now 1. so it adds 5+1=6*sizeof(*arr.elements) here the value of sizeof(*arr.elements)=4 as *arr.elements are declared int*. so it reallocates 6*4=24 byte memory,for each integer it takes 4 bytes.So the total int elements are 6.and all the elements value becomes 0 by default . If you don't know the use of realloc ,have a look at this: https://www.tutorialspoint.com/c_standard_library/c_function_realloc.htm 2.In this line, if (arr.size < arr.cap) { arr.elements[arr.size] = 50; /* add element to array */ arr.size++; here the value of arr.size is 0 as decalred at the beginning . The value of arr.cap=5+1=6 as the expression if (arr.elements != NULL) is true. so the condition if (arr.size < arr.cap) becomes true and it adds arr.element[0]=50 Hope you understood.
6th Apr 2021, 3:33 PM
The future is now thanks to science
The future is now thanks to science - avatar
+ 2
The future is now thanks to science thanks for full explanation ⭐⭐
6th Apr 2021, 3:35 PM
RAJESH
+ 1
Which part in particular you need explanation for?
6th Apr 2021, 3:15 PM
Ipang