+ 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?
6 Respostas
+ 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.
+ 4
(*p). is equivalent to p->
+ 1
Got it Schindlabua
Big Thanks for this 👍
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.
0
To get the address of something, use `&`:
&((recs+k)->info)
Or just
&(recs+k)->info
0
schindlabua
thank u