2021寒假专题3

这个专题主要关于结构,联合,枚举以及typedef

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


struct student
{
	char name[20];//以最长数据类型作为单位,类型不同就会有浪费,数组仍然是以单位来对齐 
	int age;
};

struct A
{
	char a;//采用偶数对齐的方式,不能跨偶数,多个较小的数据可以放在一个大的数据空间里 
	char b;
	short c;
	int d;
};

struct B
{
	
	int  b:17;
	int  a:1;
}; 


//将一个结构作为参数
//用指针传递效率更高,不把结构直接传过去 
void f(struct student* st)
{
	printf("%s",st->name);
} 

int main()
{
	
	printf("%d",sizeof(struct B));
	
	
	struct student *p=(struct student*)malloc(sizeof(struct student));
	p->age=30;
	strcpy(p->name,"Marry");
	f(p);
	free(p->name);//释放空间注意先后顺序 
	free(p);

	//struct student *p=(struct student*)calloc(5,sizeof(struct student));//结构数组 
	//p[1]->age=20;
		
}

include <stdio.h>

        //联合
//所有变量一个地址   
//空间取决于最大类型的空间
//联合的内部变量慎用指针,否则就只能先用这个空间并free,再使用其他变量 
      union A
{
	int a;
	char b;	
};
union B
{
	char *p;
	int num;
 }; 

int main()
{
	union A emp1;
	union B emp2;
	emp1.a=65;
	//printf("%d %c",emp.a,emp.b); //没有定义emp.b也有值
	emp1.b='B';
	printf("%c",emp1.b);
	emp2.p=(char *)malloc(sizeof(char)*10);
	char str[10]="Apple";
	emp2.p=str;
	printf("%s", emp2.p);
	free(emp2.p);
}

include <stdio.h>

        //枚举
//内部是整数常量,常量是不能被修改的 
//不赋值的情况下,首元素是0,其余元素往下依次递
//如果给某个常量赋值,从这个元素开始往下的元素以这个为基础进行递增 
enum 
{
	red=2,yellow,black//没有分号 
};
int main()
{
	//red=3;(wrong)
	printf("%d\n",red);
	//yellow is 3
	 
}


     typedef long long ll;//语句 定义了一个数据类型 修改起来很简单,这一点和define很像 
//define ll long long//简单替换,宏常量typedef做不到
//typedef 定义struct 
typedef struct 
{
	int a;
	int b;
}A2; 


struct A1
{
	int a;
	int b;
	
};
typedef struct A1 a1; 

 
char* mystrcat(char *s1,char *s2)
{
	strcat(s1,s2);
	return s1;
}
//写法1
/*char* test(char *(*f)(char *,char*),char* s1,char* s2)
{
	return f(s1,s2);
}*/
//写法2
typedef  char *(*STRCAT)(char*,char*);//定义这种数据结构
//STRCAT本身是一个指针,有两个参数,都是char*,返回值也是指针 
//函数返回值如果是如此复杂,typedef的作用不可代替 
char* test(STRCAT p,char* s1,char* s2)
{
	return p(s1,s2);
} 
int main()
{

	STRCAT parray[10];//定义这种类型的数组
	/*或者char *(*pparray[10])(char*,char*); */
	char s1[10]="Hello ";
	char s2[10]="World";
	char* p=test(mystrcat,s1,s2); 
	printf("%s",p);
}
posted @ 2021-01-31 19:28  empty_thought  阅读(56)  评论(0)    收藏  举报