1. 程式人生 > 其它 >36.結構體

36.結構體

結構體

1.struct是關鍵字
2.struct Student合起來才是結構體型別
3.結構體內部定義的變數不能直接賦值
4.結構體制是一個型別,沒有定義變數之前,是沒有分配空間,就不能賦值

#include<stdio.h>
#include<string.h> 
struct Student{
	int age;
	char name[50];
	int score;
};
int main()
{
	struct Student stu;
	stu.age = 19;
	//stu.name = "Mike";//這樣是錯誤的,因為name是陣列名,陣列名是常量,不可以修改
	strcpy(stu.name, "Mike"); 
	stu.score = 30;
	
	//1.結構體變數的初始化,和陣列一樣,要使用大括號
	//2.只有定義後才能初始化
	struct Student tmp = {18, "mike", 59
	};
	
	//如果是指標,指正有合法指向,才能操作結構體成員 
	struct Student *p;
	p = &tmp;
	p->age = 18;
	strcpy(p->name, "mike");
	p->score = 59;
	 
	//任何結構體變數都可以用. 或者->操作成員
	(&tmp) -> age = 18;
	(*p).age = 18; 
	
	
	
 } 
 
struct people
{
	int age;
	char name[50];
	int score;
}s1 = {18, "mike", 59}, s2;

struct
{
	int age;
	char name[50];
	int score; 
}s3, s4;

結構體陣列

#inlucde<stdio.h>
#inlucde<string.h>
//結構體陣列 
struct Student
{
	int age;
	char name[50];
	int score;
}
int main(){
	struct Student a[5];	//結構體陣列 
	a[0].age = 18;
	strcpy(a[0].name, "mike");
	a[0].score = 59;
	
	(a + 1) -> age = 19;
	strpcy((a + 1)->name, "jiang");
	(a + 1) -> score = 69;
	
	(*(a + 2)).age = 20;
	strcpy((*(a + 2)).name, "lily");
	(*(a + 2)).score = 79;
	
	struct Student *p = a;
	p = &a[0];
	
	p[3].age = 21;
	p[3].score = 49;
	strcpy(p[3].name, "xiaoming");
	
	(p + 4) ->age = 22;
	strcpy((p + 4)->name, "xiaojiang");
	(p + 4)->score = 88;
	
	int i = 0;
	int n = sizeof(a)/sizeof(a[0]);
	for(i = 0; i < n; i++)
	{
		printf("%d, %s, %d", a[i].age, a[i].name, a[i].score);
	}
} 

結構體的巢狀

#include<stdio.h>
struct Student
{
	struct info;
	int score;
 };
struct info{
	int age;
	char name[50];
};
int main()
{
	struct Student s;
	s.info.age = 18;
	strcpy(s.info.name, "mike");
	s.score = 59;
	
	struct Student *p = &s;
	p->info.age = 18;
	strcpy(p->info.name, "mike");
	p->score = 59;
	
	struct Student tmp = {18, "mike", 59};
	printf("%d, %s, %d", tmp.info.age, tmp.info.name, tmp.score);
}