Reputation: 13
I don't understand some piece of code in C, and couldn't find any similar question, so I hope you'll help me.
I have a struct
table defined like this:
struct my_struct {
struct other_struct some_struct[N];
char some_char;
..
} my_struct[N];
In another function:
struct my_struct *ms;
And then is the part I don't understand:
ms = &my_struct[0];
How can I interpret this line?
Upvotes: 1
Views: 3259
Reputation: 30926
ms
is a pointer to the struct my_struct
. It contains address of a struct my_struct
variable. Here we assign to ms
the already declared struct my_struct
array's (also name my_struct
) 0-th element's address.
&
- address of operator. Which basically returns the address of a variable.
Now you can access my_struct[0]
via ms
.
Equivalently
ms->some_char = 'A'
is same as my_struct[0].some_char='A'
. To give a small example I can simplify this way.
struct a{
int z;
};
struct a array[10]; // array of 10 `struct a`
struct a* ptr = &array[0]; // ptr contains the address of array[0].
Now we can access array[0]
via pointer ptr
.
And ms
is just a pointer to struct
not pointer to a table of struct
as you have mentioned in the question heading.
Upvotes: 2