C언어

[ C언어 ] 구조체

괴발새발개발자 2021. 7. 1. 02:59
#include <stdio.h> 
#include <string.h>

struct student{
	int number;
	char name[10];
	double grade;
};

int main(){
	struct student s;
	
	s.number = 20070001;
	strcpy(s.name, "홍길동");
	s.grade = 4.3;
	
	printf("학번: %d\n", s.number);
	printf("이름: %s\n", s.name);
	printf("학점: %lf\n", s.grade);
	
	return 0;
} 

// 출력
학번: 20070001
이름: 홍길동
학점: 4.300000

// 사용자 정의 자료형
// 내가 직접 만드는 자료형

1. 구조체 선언
typedef struct student{
// 멤버변수
int number;
char name[20] ;
}STUDENT; 

2. 구조체 변수 선언
struct student s1;
STUDENT s2;
STUDENT s3;

3. 구조체 변수 활용
STUDENT student;
student.number = 1;
// student.name = "abc" ; // 에러 발생!!!! 
strcpy(student.name, "abc");

printf("%d %s", student.number, student.name);

4. 구조체 배열
자료형 변수이름[ ] 
STUDENT s [5];
int arr[5] = {1,2,3,4,5}; // 초기화
int arr[5]; // 초기화 X
arr[0] = 1;
arr[1] = 2;
...........
s[0].number = 1;
s[0].name = "홍길동" ;
strcpy(s[0].name, "홍길동");

=================================================
while(조건식){


}

for(i=0; i<10; i++){
s[i].number = i;
}