C-结构体类型要点

不要直接对结构体内数组赋值,数组在任何地点都是常量

#include 
#include 
#include 
typedef struct student{
	char name[5];
	int age;
}stu;
int main(){
	stu *p=(stu*)malloc(sizeof(stu));
	p->age=18;
	strcpy(p->name,"tom");//由于为数组不能使用p->name="" 进行赋值
	printf("%s",p->name);
	system("pause");
}
int a=3;

*的优先级低于.请加()

#include 
#include 
#include 
typedef struct student{
	char name[5];
	int age;
}stu;
int main(){
	stu s1={"tom",18};
	stu *s2=&s1;
	//下面通过s2指针来访问
	printf("%s",s2->name);
	printf("%s",(*s2).name);//.优先级>*请使用()

	system("pause");
}
int a=3;

结构体数组

#include 
#include 
#include 
typedef struct student{
	char name[5];
	int age;
}stu;
int main(){
	stu s1[2]={
		{"tom",18},
		{"jam",18}
	};
	//下面通过s2指针来访问
	printf("%s",(s1+1)->name);
	printf("%s",s1[1].name);
	printf("%s",(*(s1+1)).name);//.优先级>*必须加()
	system("pause");
}
int a=3;

结构体的嵌套

#include 
#include 
#include 
typedef struct student{
	char name[5];
	int age;
}stu;
typedef struct math{
	stu s;//stu *s 是不可以的 应为是野指针
	int score;
};
int main(){
	struct math m[2]={
		{"tom",18,99},
		{"jam",20,80}
	};
	int i=0;
	for(i=0;i<2;i++){
		printf("%s\n",m[i].s.name);
	}
	system("pause");
}

相同类型结构体可以相互赋值 但都是相互独立的内存空间

#include 
#include 
#include 
typedef struct student{
	char name[5];
	int age;
}stu;
typedef struct math{
	stu s;//stu *s 是不可以的 应为是野指针
	int score;
};
int main(){
	struct math m={"tom",18,99};
	struct math m2=	m;
	printf("%s\n",m2.s.name);
	system("pause");
}

结构体与函数

#include 
#include 
#include 
typedef struct student{
	char name[5];
	int age;
}stu;
void setM(stu m){//本质上还是在栈区开辟了一个临时变量函数指向结束后就销毁
	m.age=19;
	strcpy(m.name,"jam");
	printf("%s\n",m.name)//jam;
}
int main(){
	stu m={"tom",18};
	setM(m);
	printf("%s\n",m.name);//tom
	system("pause");
}

你可能感兴趣的:(#,C/C++)