结构体相关笔记

                                                                                                                                                      一、结构体:

1、结构体的定义:

(1)

	struct date{
		int month;
		int day;
		int year;
	};

(2)对一个变量的定义:

a.

	struct date{
		int month;
		int day;
		int year;
	}today,tomorrow;

b. 

    struct date today;
    struct date tomorrow;

2、赋值:

(1)

	struct date today = {10,12,2021};

(2)

    struct date today = {.month=12,.year=2021};

(3.1)结构体可以直接用“ = ”赋值,使用前today和tomorrow需定义

a.正确

	today = (struct date){12,10,2021}; 
	tomorrow = today;

 b.错误(虽然也能编译通过,且输入输出正确,但是会有警告)

    today = {12,10,2021}; 
    tomorrow = today;
  [Warning] extended initializer lists only available with -std=c++11 or -std=gnu++11

 (3.2)接(3.1)此时若

    tomorrow.day = 11;

输出时today保持不变,所以结构变量的名字并不是结构变量的地址,必须要用& 

(4)

	struct date today;
	scanf("%i%i%i",&today.month ,&today.day ,&today.year );

ps.

(1)用" . "来访问结构里的变量;

(2)若未赋值到,就是0;

3、结构指针:

	struct date *p = &today;

4、结构函数 :

(1)因为结构名不等于数组名是一个指针,所以不能像数组一样操作;

(2)传入结构,返回结构:

a,

#include 
struct point {
	int x;
	int y;
};
struct point limb(struct point p){
	scanf("%d",&p.x);
	scanf("%d",&p.y);
	printf("%d %d\n",p.x ,p.y );
	return p;
}
int main(void)
{
	struct point b={1,2};
	limb(b);
	printf("%d %d\n",b.x ,b.y );
	return 0;
 } 

输入输出: 

2 4
2 4
1 2

--------------------------------
Process exited after 2.322 seconds with return value 0
请按任意键继续. . .

b.

#include 
struct point {
	int x;
	int y;
};
struct point limb(void){
	struct point p;
	scanf("%d",&p.x);
	scanf("%d",&p.y);
	printf("%d %d\n",p.x ,p.y );
	return p;
}
int main(void)
{
	struct point b;
	limb();
	printf("%d %d\n",b.x ,b.y );
	return 0;
 } 

输入输出:

2 4
2 4
0 0

--------------------------------
Process exited after 3.001 seconds with return value 0
请按任意键继续. . .

 (3)传入指针,传出指针:

注:指向结构中成员的指针

struct point {
	int x;
	int y;
}p;
struct point *p1 = &p;
(*p1).x=2;
p1->x = 2;//二者相同 
#include 
struct point {
	int x;
	int y;
};
struct point limb(struct point p){
	scanf("%d",&p.x);
	scanf("%d",&p.y);
	printf("%d %d\n",p.x ,p.y );
	return p;
}
int main(void)
{
	struct point b={1,2};
	limb(b);
	printf("%d %d\n",b.x ,b.y );
	return 0;
 } 

输入输出:

2 4
2 4
2 4

--------------------------------
Process exited after 1.903 seconds with return value 0
请按任意键继续. . .

(4)结构数组:

struct point a[100];
struct point b[]={{4,5},{6,7}};
for(i=0;i<2;i++){
printf("%d %d",b[i].x,b[i].y);
}

(5)结构嵌套:

struct point {
	int x;
	int y;
}; 
struct POINT {
	struct point a;
	struct point b;
};
//如果有变量 c 
struct POINT c;
//那么就可以有
c.a.x ;
c.a.y ;
c.b.x ;
c.b.y ;

(6)几种等价形式:

//如果有
struct POINT r,*rp;
rp=&r;
//那么以下四种形式等价
r.a.x ;
rp->a.x ;
(r.a).x ;
(rp->a).x ; 

(7)结构数组嵌套(接上文):

struct POINT arry[]={{{1,2},{3,4}},{{5,6},{7,8}}};

你可能感兴趣的:(编程学习笔记,gnu,p2p,debian)