Fagun
Fagun

Reputation: 35

Structure pointer and its use

What is the meaning of this statement in C?

where fag is structure and its pointer is pat.

fag *pat = &h.device[d];
d = (pat - &(h.device[0]))/(sizeof(fag)) ;

Upvotes: 3

Views: 107

Answers (2)

glglgl
glglgl

Reputation: 91017

fag *pat = &h.device[d];

takes the address od the dth element of the said array.

It can be used to ease the access to it.

If I do

d = (pat - &(h.device[0]))/(sizeof(fag));

where I don't have access to the original d, I get the index of the given entry, in the said array.

It takes the difference from "our" pointer to the original one.

If I see it right, the division by sizeof fag is wrong - the difference is already in terms of fag size. Besides, &(h.device[0]) is exactly the same as h.device, so

d = pat - h.device;

should be the right thing. (Thank you, WhozCraig.)

Upvotes: 4

Ansh David
Ansh David

Reputation: 672

One possible use of a structure pointer might be that if you want to change the members of a struct in a function, you have to pass the struct's address.

Upvotes: 0

Related Questions