访问结构成员:
1.
int main()
{
struct test
{
int a = 0;
int b = 1;
int c = 3;
};
struct test one;
printf("%d\n", one.c);
return 0;
}
此时的输出为:
对结构体成员的直接访问;
2.
int main()
{
int a = 1;
struct test
{
int a;
int b = 0;
};
struct test one;
printf("%d\n", one.a);
return 0;
}
此时输出结果为:
并不是 此前定义的a=1;
这是因为:在struct里面的a是局部变量,而表达式:one.a访问的是struct中的局部变量a。这个a 并未初始化,所以只能访问其此时的地址。
当我们访问b时,输出结果就是在struct中初始化b 的值。
3.
#include<stdio.h>
int main()
{
struct test
{
int a[20] ;
int b = 0;
};
struct test one;
printf("%d\n", one.a);
return 0;
}
当a现在被定义为 数组时,输出结果是:
就是a的地址。
4.
int main()
{
struct test
{
int a[20] = {1,2,3,4,5,6,7,8,9};
int b = 0;
};
struct test one;
printf("%d\n", one.a[0]);
return 0;
}
当访问struct中数组的具体元素时,结果是:
就是改位置存放的值。
5.当结构体中还有结构体,并且需要访问里层结构体的元素:
int main()
{
struct test
{
int a[20] = {1,2,3,4,5,6,7,8,9};
int b = 328742;
};
struct test2
{
struct test one;
int c = 1;
};
test2 two;
printf("%d\n", two.one.b);
return 0;
}
用到了两层调用,通过前面的例子可知,struct里面的变量均为局部变量,所以语句:
struct test one;
必须在
struct test2
里面定义,否则访问不到。
two.one.b
进行两个访问,先访问two 中的one ,相当于从结构体two中进入到结构体one 中,然后one.b表示直接访问one 中的变量b,
最后,成功访问到b。
输出结果 如下:
6.访问里层结构体中的数组成员:
int main()
{
struct test
{
int a[20] = {1,2,3,4,5,6,7,8,9};
int b = 328742;
};
struct test2
{
struct test one;
int c = 1;
};
test2 two;
printf("%d\n", two.one.a);
return 0;
}
结果为
这个所谓a的地址的结果每次都不一样,不必纠结。
int main()
{
struct test
{
int a[20] = {1,2,3,4,5,6,7,8,9};
int b = 328742;
};
struct test2
{
struct test one;
int c = 1;
};
test2 two;
printf("%d\n", two.one.a[2]);
return 0;
}
结果: