码迷,mamicode.com
首页 > 其他好文 > 详细

C——结构体总结

时间:2015-06-01 11:42:15      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:c   c语言   

结构体定义和结构体变量的声明

方式一:

定义,初始化结构体变量分开

struct Student
{
	char name[10];
	char age;
};

struct Student stu;


方式二:

附加结构体变量初始化

struct Student
{
	char name[10];
	char age;
}stu;


方式三:

struct
{
	char name[10];
	char age;
}stu;

把结构体名称去掉,这样更简洁,不过也不能定义其他同结构体变量了。


结构体内部成员变量

结构体内部成员变量的赋值:

方式一:

struct Student stu = {"hyk", 25};
struct Student stu = {.age = 25, .name = "hyk"};

方式二:

struct Student stu;
strcpy(stu.name, "hyk");
stu.age = 25;

方式三:

struct Student stu = { "hyk", 25 };
struct Student stu2 = stu;// 实际是两个结构体内存的拷贝,将stu内存的值拷贝给了stu2,如果结构体成员有指针元素,那么就不能直接赋值。


一个结构中可以有数组成员,也可以有指针成员,如果是指针成员结构体成员在初始化和赋值的时候就需要提前为指针成员分配内存。


指定结构体元素的位字段

定义一个结构体时可以指定具体元素的位长。

struct Test{
	char a : 2;//指定元素为2位长,不是2个字节长
};


结构体数组

struct Student
{
	int a[3];
	int b;
};

int main() {

	struct Student stu[3] = {
		{ {1, 2, 3 }, 10 },
		{ {4, 5, 6 }, 11 },
		{ {7, 8, 9 }, 12 }
    };

	// 可以简写为:
	struct Student stu[3] = {
		{ 1, 2, 3, 10 },
		{ 4, 5, 6, 11 },
		{ 7, 8, 9, 12 }
	};

	return 0;
}


结构体与指针

struct Student stu;
struct Student *p = &stu;
p->age = 26;


结构体数组与指针

栈数组:

struct Student
{
	int a;
	int b;
};

int main() {

	struct Student stu[3];
	struct Student *p = stu;

	int i;
	for (i = 0; i < 3; i++) {
		p->a = 10 + i;
		p->b = 20 + i;
		p++;
	}

	printf("%d,%d\n", stu[0].a, stu[0].b);
	printf("%d,%d\n", stu[1].a, stu[1].b);
	printf("%d,%d\n", stu[2].a, stu[2].b);
	return 0;
}

运行结果:

技术分享

堆数组:

struct Student
{
	int a;
	int b;
};

int main() {

	struct Student *p;
	p = malloc(sizeof(struct Student) * 3);
	struct Student *arr = p;//arr指针记录了p的初始指针
	p->a = 1;
	p->b = 2;
	p++;// 导致p指针的位置发生偏移,
	p->a = 3;
	p->b = 4;
	
	printf("%d,%d\n", arr[0].a, arr[0].b);
	printf("%d,%d\n", arr[1].a, arr[1].b);

	//free(p);// 因为p的指针发生偏移,free(p)会发生异常
	free(arr);// 可以正常释放malloc申请的堆内存
	return 0;
}

运行结果:

技术分享


结构体成员内存对齐图解

技术分享


结构体嵌套对齐图解:

技术分享



C——结构体总结

标签:c   c语言   

原文地址:http://blog.csdn.net/wuseyukui/article/details/46291735

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!