结构体对齐和深拷贝浅拷贝

-------------------结构体对齐-----------------------

#include<stdio.h>
#include<stdlib.h>

struct info
{
	//结构体变量的大小能够被其最宽基本类型成员的大小锁整除
	//22  同类型不需要加在一起
	short sh1; //2   最宽基本类型
	char sh2;  //1
	char ch[19];//19+1
	//28
	short sh3;//2+2   2,不足  补2
	int sh4;  //4   最宽基本类型
	char ch1[19];//19+1
};

void main1()
{
	printf("%d", sizeof(struct info));
	getchar();
}

struct info1
{
	short sh1;  //2+2
	int sh2;    //4
	char ch[19];//19+1  结构体数组不算基本类型
};
void main2()
{
	struct info1 info11 = { 10,200,"123456" };
	printf("%p\n", &info11);    //00AFF980
	printf("%p\n", &info11.sh1);//00AFF980
	printf("%p\n", &info11.sh2);//00AFF984
	printf("%p\n", &info11.ch); //00AFF988

	getchar();
}




--------------------深拷贝浅拷贝--------------------------

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>


struct string
{
char *p;
int length;
};


void mainA()//浅拷贝,共用一片内存
{
struct string str1;
str1.length = 10;
str1.p = (char*)malloc(sizeof(char) * 10);
strcpy(str1.p, "hello");//拷贝字符串到str1.p中
printf("%s\n", str1.p);


struct string str2;
str2.length = str1.length;
str2.p = str1.p;
*(str1.p) = 'q';
printf("str1=%s\n", str1.p);//qello
printf("str2=%s\n", str2.p);//qello
//浅拷贝,共用一片内存
getchar();
}


void main()//深拷贝,互不干涉
{
struct string str1;
str1.length = 10;
str1.p = (char*)malloc(sizeof(char) * 10);
strcpy(str1.p, "hello");//拷贝字符串到str1.p中
printf("%s\n", str1.p);


struct string str2;
str2.length = str1.length;
str2.p = (char*)malloc(sizeof(char) * 10);//单独开辟内存
strcpy(str2.p, str1.p);//str1.p拷贝到str2.p
*(str1.p) = 'q';
printf("str1=%s\n", str1.p);//qello
printf("str2=%s\n", str2.p);//hello


getchar();
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值