Computer >> 컴퓨터 >  >> 프로그래밍 >> C 프로그래밍

C언어 구조체(Structure) 변수 접근 방법 총정리

구조체(structure)는 사용자가 직접 정의하는 데이터 타입으로, 서로 다른 자료형의 데이터를 하나로 묶어 저장할 수 있는 기능을 제공합니다.

구조체는 배열과 비슷하지만 결정적인 차이가 있습니다. 배열은 동일한 자료형의 데이터만 저장할 수 있는 반면, 구조체는 서로 다른 자료형의 데이터를 함께 저장할 수 있습니다.

구조체를 선언할 때는 struct 키워드를 사용하며, 구조체 내부에 선언된 변수들을 멤버(member)라고 부릅니다.

구조체 선언 방법

구조체는 다음과 같은 형식으로 선언합니다.

struct 구조체이름 {
    // 멤버 선언
};

구조체 멤버 접근 예제

아래는 C언어에서 구조체 변수의 멤버에 접근하는 방법을 보여주는 프로그램입니다. 점 연산자(.)를 사용하여 구조체 변수의 각 멤버에 접근할 수 있습니다.

#include<stdio.h>

// 구조체 선언 및 변수 정의 //
struct {
    char name[50];
    int roll;
    float percentage;
    char grade[50];
} s1, s2;

int main() {
    // 사용자 입력 받기 //
    printf("enter Name of 1st student : ");
    scanf("%s", s1.name);
    printf("enter Roll number of 1st student : ");
    scanf("%d", &s1.roll);
    printf("Enter the average of 1st student : ");
    scanf("%f", &s1.percentage);
    printf("Enter grade status of 1st student : ");
    scanf("%s", s1.grade);

    // 결과 출력하기 //
    printf("The name of 1st student is : %s\n", s1.name);
    printf("The roll number of 1st student is : %d\n", s1.roll);
    printf("The average of 1st student is : %f\n", s1.percentage);
    printf("The student 1 grade is : %s and percentage of %f\n", s1.grade, s1.percentage);

    return 0;
}

코드 설명

  • s1.name, s1.roll처럼 구조체변수명.멤버명 형태로 각 멤버에 접근합니다.
  • intfloat 멤버를 입력받을 때는 주소 연산자(&)를 붙여야 합니다.
  • 문자열 배열인 name, grade는 그 자체가 주소이므로 & 없이 사용합니다.

참고: 원본 코드에 있던 gets() 함수는 버퍼 오버플로우 위험 때문에 C11 표준부터 제거되었으므로, 안전한 scanf()fgets() 사용을 권장합니다. 또한 void main()보다는 표준에 맞는 int main()을 사용하는 것이 좋습니다.

실행 결과

위 프로그램을 실행하면 다음과 같은 결과가 출력됩니다.

enter Name of 1st student: Bhanu
enter Roll number of 1st student: 2
Enter the average of 1st student: 68
Enter grade status of 1st student: A
The name of 1st student is: Bhanu
The roll number of 1st student is: 2
The average of 1st student is: 68.000000
The student 1 grade is: A and percentage of 68.000000

마무리

C언어에서 구조체는 서로 다른 자료형을 하나의 단위로 관리할 수 있게 해주는 강력한 도구입니다. 점 연산자(.)를 이용해 구조체 멤버에 접근하는 방법은 구조체 활용의 가장 기본이 되므로 반드시 숙지해 두시기 바랍니다.