方法(一):定义时赋值

# include <stdio.h>
struct AGE
{
    int year;
    int month;
    int day;
};
struct STUDENT
{
    char name[20];
    int num;
    struct AGE birthday;
    float score;
};
int main(void)
{
    struct STUDENT student1 = {"小明", 1207041, {1989, 3, 29}, 100};
    return 0;
}

方法(二):定义后赋值

# include <stdio.h>
# include <string.h>
struct AGE
{
    int year;
    int month;
    int day;
};
struct STUDENT
{
    char name[20];  //姓名
    int num;  //学号
    struct AGE birthday;  /*用struct AGE结构体类型定义结构体变量birthday, 即生日*/
    float score;  //分数
};
int main(void)
{
    struct STUDENT student1;  /*用struct STUDENT结构体类型定义结构体变量student1*/
    strcpy(student1.name, "小明");  //不能写成&student1
    student1.num = 1207041;
    student1.birthday.year = 1989;
    student1.birthday.month = 3;
    student1.birthday.day = 29;
    student1.score = 100;
    printf("name : %s\n", student1.name);  //不能写成&student1
    printf("num : %d\n", student1.num);
    printf("birthday : %d-%d-%d\n", student1.birthday.year, student1.birthday.month, student1.birthday.day);
    printf("score : %.1f\n", student1.score);
    return 0;
}

方法(三):构造函数初始化

利用 memset(d,0,sizeof(d))初始化

struct bign{
	int d[1000];//位数 
	int len;//实际位数长度 
	bign(){
	     memset(d,0,sizeof(d));//数组d 长度d赋值为0
	     len=0;		
	}
};

方法(四):利用构造函数赋值

#include <stdio.h>
int main(){
	struct Test{
		int num=1;
		int count=2;
	
		Test(int _num,int _count):num(_num),count(_count){ //构造函数变量不能与成员变量名相同 
			
	    }
	}test(1,2); //1,2就是传入的参数。
    //Test test=Test(1,2); 依然成立
	printf("%d",test.count);   //2 
	return 0;
}

练习:初始化平面点的坐标

#include <stdio.h>
struct Point{
	int x;
	int y;
	Point(){   //用于定义p[10],去除则会报错
	}
	Point(int _x,int _y):x(_x),y(_y){
		
	}
}p[10];
int main(){
	int num=0;
	for(int i=1;i<=3;i++){
		for(int j=1;j<=3;j++){
			p[num++]=Point(i,j);
		}
	}
	for(int i=0;i<num;i++){
		printf("%d,%d\n",p[i].x,p[i].y);
	}
	return 0;
} 

答案:
1,1
1,2
1,3
2,1
2,2
2,3
3,1
3,2
3,3

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐