달력

5

« 2024/5 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
2015. 9. 4. 17:43

구조체의 정의 프로그래밍/C언어2015. 9. 4. 17:43

구조체를 사용함으로써 여러 변수를 하나로 묶어 새로운 자료형을 정의 할 수 있다.

 


-구조체 정의

struct     자료형_이름

{

   변수 선언1;

   변수 선언2;

   변수 선언3;

};


배열도 변수이기 때문에 구조체의 멤버가 될 수 있다.

 



-구조체 변수 선언

struct      자료형_이름    변수_이름;


또는 다음과 같이 구조체를 정의함과 동시에 구조체 변수를 선언 할 수 있다.


struct     자료형_이름

{

   변수 선언1;

   변수 선언2;

   변수 선언3;

}변수_이름1, 변수_이름2, 변수_이름3;




-구조체 변수의 초기화

구조체 변수의 초기화 방법은 배열의 초기화와 유사하다.

단순히 멤버의 순서대로 초기화할 대상을 나열하면 된다.

그래서 초기화 과정에서는 문자열 저장을 위해서 strcpy()함수를 호출 하지 않아도 된다.

 



-구조체 변수의 멤버에 접근

​구조체_변수_이름.멤버_이름




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <stdio.h>
#include <string.h>
 
struct person //구조체 정의
{
    char name[20];
    char phoneNumber[20];
    int age;
}man1, man2; //구조체 변수 선언
 
int main(void)
{
    //struct person man1, man2; //구조체 변수 선언
        
    /*구조체 변수의 초기화*/
    struct person man3 = {"홍길동""010-1234-8697", 84};     
    
    /*구조체 멤버에 접근*/
    strcpy(man1.name,"안유진");
    strcpy(man1.phoneNumber,"010-4085-8697");
    man1.age = 23;
        
    /*구조체의 scanf 사용*/
    printf("이름을 입력하세요: "); scanf("%s", man2.name);
    printf("전화 번호를 입력하세요: "); scanf("%s", man2.phoneNumber);
    printf("나이를 입력하세요: "); scanf("%d", &man2.age);
 
    /*구조체의 printf 사용*/
    printf("이름: %s \n", man1.name);
    printf("전화번호: %s \n", man1.phoneNumber);
    printf("나이: %d\n\n", man1.age);
 
    printf("이름: %s \n", man2.name);
    printf("전화번호: %s \n", man2.phoneNumber);
    printf("나이: %d\n\n", man2.age);
 
    printf("이름: %s \n", man3.name);
    printf("전화번호: %s \n", man3.phoneNumber);
    printf("나이: %d\n", man3.age);
    
    return 0;
}


:
Posted by youjin.A