Reputation: 33
foo
is a struct
with 5 scalar variables (A
, B
, C
, D
, F
) and one array (E
). What is confusing me is what f[0]
, f[1]
, and f[2]
are in this context and what is happening here.
int
bar(struct foo *f)
{
f[1].C = f[0].B > f[2].C;
f[0].E[-1] = f[0].D;
f[0].A = f[1].C;
}
Are f[0]
, f[1]
, and f[2]
individual structures with member variables? Can someone please explain? Thanks.
Upvotes: 3
Views: 128
Reputation: 22290
What you are doing is, you are passing a reference (pointer) to an array of struct foo
to the function bar
.
You must somewhere have a code that is similar to following:
struct foo myFoos[10]; // an array with 10 elements of struct foo
struct foo *mallocedFoos;
// here goes some code to initialize the elements of the array
bar(&myFoos[0]); // pass a reference to (address of/pointer to) the array
// or something like this is happening
mallocedFoos = malloc(sizeof(struct foo) * 10);
// here goes some code to initialize allocated memory
bar(mallocedFoos); // pass the 'struct foo *' to the function
To understand the concept better, see this example.
Upvotes: 2
Reputation: 7437
Yes, in this context, f[0]
, f[1]
, etc., are elements of an array of type struct foo
.
The more interesting thing to me is this line:
f[0].E[-1] = f[0].D;
I didn't realize negative indexes were allowed, but this question explains that array indexing is just pointer math, so it's an obfuscated way of saying:
f[0].D = f[0].D;
Which is basically useless as far as I know.
Also interesting:
f[0].C = f[0].B > f[2].C;
This would set f[0].C
to a boolean, which is not usually compared with a >
operator, so it's possible that different C
members are used for different functions.
I feel that your confusion is warranted, given the strange nature of this function.
Upvotes: 2
Reputation: 5361
In this case f
is an array of structures
Similar to
struct node = {
int A; //A to D and F are scalar variables
int B;
int C;
int D;
int E[10]; //E is an array of integers
int F;
}
struct node f[10]; //f is an array of structs
For more details you can also refer How do you make an array of structs in C?
Upvotes: 1
Reputation: 400522
Are
f[0]
,f[1]
, andf[2]
individual structures with member variables?
Yes. f
is a pointer to an array of struct foo
instances f[0]
is the first such member of that array, f[1]
is the second member, etc. You might call it like this:
struct foo fArray[3];
// ... Initialize fArray[0], fArray[1], fArray[2] etc. ...
bar(fArray);
Upvotes: 2