using calloc in c | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

using calloc in c

this is an example from C course on solo learn note> struct record is a structure. 1> struct record *recs; 2> int num_recs = 2; 3> int k; 4> recs = calloc(num_recs, sizeof(record)); 5> if (recs != NULL) { 6> for (k = 0; k < num_recs; k++) 7> (recs+k)->num = k;}}} in the above code 'recs' is declared as a pointer variable, but on the seventh line, they didn't use the dereferencing operator like: *(recs+k) to store the value. when I am using the * operator it is giving an error?

22nd Aug 2019, 7:31 PM
Kesh∆v
Kesh∆v - avatar
6 Answers
+ 4
It's a pointer to a struct, `recs+k` being a pointer that points to the `k`-th record. If we want to set the `num` member of that we have to dereference, as you said. There's 2 ways: (*(recs+k)).num = k; Here we are quite literally dereferencing the pointer and then accessing `num`. But then there's also the shorthand using the arrow that does exactly the same: (recs+k)->num = k; So, the arrow is like the dot but it works on pointers to structs, instead of structs themselves.
22nd Aug 2019, 11:08 PM
Schindlabua
Schindlabua - avatar
+ 4
(*p). is equivalent to p->
23rd Aug 2019, 2:04 AM
Sonic
Sonic - avatar
+ 1
Got it Schindlabua Big Thanks for this 👍
23rd Aug 2019, 1:00 AM
Ipang
0
This is just how I see it, I could be wrong ... <recs> is a structure array, a block of memory that can be mapped into multiple instances of 'record' structure, we don't use dereference operator directly on <recs + k>, because it is not something that can be translated into a value (structures have members). And we want to change its member's value here (<num> member), not the structure. I think it doesn't make much of a sense to try to dereference a structure since it is a container, that's how I see it. Again, I could be wrong, looking forward to experts' opinions on this, while I try to search : ) (Edit) Schindlabua got it covered.
22nd Aug 2019, 8:36 PM
Ipang
0
To get the address of something, use `&`: &((recs+k)->info) Or just &(recs+k)->info
23rd Aug 2019, 10:50 AM
Schindlabua
Schindlabua - avatar
0
schindlabua thank u
23rd Aug 2019, 11:52 AM
Kesh∆v
Kesh∆v - avatar