It's not entirely clear what you're expecting to see as output from the code you've posted. If you expect to see "25", then you're right on. Accessing members of your structure the way you're attempting to do, while "valid" in this particular case, can be very hazardous unless you know exactly what you're doing. Consider the following minor change to your structure:
struct
{
int x;
char y;
} s[] = {10,20,15,25,8,75,6,2};
What do you think your code would get now? The simple answer is "it depends." On what, you ask? On the size of a char
in your chosen system's architecture. It's usually 8 bits, but that's not guaranteed. ANSI C and C99 define char
as follows:
"An object declared as type char
is
large enough to store any member of
the basic execution character set."
It also depends on how your particular compiler "aligns" the members of the structure. The compiler will generally align members on word boundaries but, again, what that means depends on the size of a "word." The structure could also be aligned on byte boundaries. The point is, there are better ways to access data in structures. Consider:
#include <stdio.h>
int main()
{
struct
{
int x, y;
} *ps, s[] = { {10, 20}, {5, 25}, {8, 75}, {6, 2} };
ps = s;
printf( "%d\n", *(ps + 3) );
printf( "%d\n", s[3].x );
printf( "%d\n", (ps + 3)->x );
return 0;
}
In this example, ps
is declared as a pointer to the unnamed structure. After making the assignment ps = s
, ps
points to the first structure member. If you add 1 to ps
, as in ps += 1;
, it will point to the second structure member, and so forth. So, in the example, all three printf
statements print the number 6. Can you see why? In the first case, *(ps + 3)
, as demonstrated when we add to ps
, we're advancing the pointer through the array of structures so it points to the third element. In the second case, s[3].x
, we're referring the the third element in the array of structures s
, and taking the value of x
in that element. Finally, (ps + 3)->x
, we add three to ps
as before then, dereferencing it as a pointer to our struct type, we take the value of x
.
Also note the way I've initialized s
. While the inner braces are not required, they're good form. If you had a more complex structure, it would be very hard to do a correct initialization without the braces to help as a guide, and for someone following after, it would be impossible to read.