Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
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
Tags more
Archives
Today
Total
관리 메뉴

냥집사의 개발일지

C언어 - 구조체 포인터 & 구조체 배열 (struct pointer & struct array) 본문

C언어

C언어 - 구조체 포인터 & 구조체 배열 (struct pointer & struct array)

깅햄찌 2022. 9. 25. 12:02
반응형

안녕하세요 오늘은 구조체 포인터와 구조체 배열에 대해 정리해보겠습니다. 

 

1. 구조체 포인터 와 '->'연산자

다들 아시다 시피 당연히 포인터 변수가 구조체를 가리킬 수 있겠죠.

이때 구조체 포인터 변수는 '->' 연산자를 통해 구조체 멤버 변수에 접근할 수 있습니다. 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct profile{
    char name[10]; 
    int age;
    char *introduction;
};


int main(){
    struct profile me = {"Jeff", 20, NULL};
    me.introduction = (char *)malloc(100 * sizeof(char));   
    strcpy(me.introduction, "hello_Jeff");
    struct profile *me_pointer = &me;

    printf("name           : %s\n", (*me_pointer).name);
    printf("age            : %d\n", me_pointer->age);
    printf("introduction   : %s\n", me_pointer->introduction);

    free(me.introduction);

    return 0;
}

1. profile 구조체 'me'를 가리키는 me_pointer 포인터를 선언합니다. 

2. 위의 코드에서 알 수 있듯이 구조체가 멤버 변수에 접근할 때는 '.' 멤버 접근 연산자를 사용하고

    구조체 포인터가 멤버 변수에 접근할 때는 '->' 연산자를 사용합니다. 

3. 아래 결과 처럼 의도한 데이터가 출력되었음을 확인할 수 있습니다. 

2. 구조체 배열

아래 코드는 구조체 배열을 초기화하고 함수의 매개변수로 받아 출력해보는 예제입니다. 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct profile{
    char name[10]; 
    int age;
    char *introduction;
};

void print_struct_arr(struct profile *friends, int size){
    for(int i=0; i<size; i++){
        printf("name           : %s\n", (friends+i)->name);
        printf("age            : %d\n", (friends+i)->age);
        printf("introduction   : %s\n", (friends+i)->introduction);
        printf("\n");
    }
}


int main(){
    struct profile friends[5] = {
        {"Jeff", 20, "hello_Jeff"},
        {"Electra", 19, "hello_Electra"},
        {"Alana", 21, "hello_Alana"},
        {"John", 19, "hello_John"},
        {"Steven", 18, "hello_Steven"}
    };
    
    print_struct_arr(friends,sizeof(friends)/sizeof(struct profile));

    return 0;
}

1. friends라는 profile 구조체 5개 요소를 가진 구조체 배열을 선언하고 초기화합니다. 

2. print_struct_arr 함수에 매개변수로 구조체 배열을 받고 '->' 연산자를 이용해 멤버 변수들을 출력합니다. 

3. 아래 결과 처럼 의도한 data들이 정상적으로 출력됐음을 확인할 수 있습니다. 

 

3. 자기 참조 구조체

자료구조를 공부하면 가장 먼저 배우는 연결 리스트가 바로 자기 참조 구조체의 대표적인 예시인데요.

아래 코드를 같이 살펴보시죠~

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct list{
    int num;
    struct list *next;
};

void print_list(struct list *current){ // current : current point of list
    while(current != NULL){
        printf("%d ",current->num);
        current = current->next;
    }
}

int main(){
    struct list a = {1,0}, b = {2,0}, c = {3,0};
    struct list *head; //head : intital point of list 

    head = &a;
    a.next = &b;
    b.next = &c;
    
    print_list(head);

    return 0;
}

1. 구조체 list의 변수 3개 a, b, c를 선언하고 구조체 list의 포인터 변수 head를 선언합니다. 

2. head는 a를, a는 b를, b는 c를 가리킵니다. 

3. print_list 함수로 list의 멤버 변수 num를 순회하며 출력합니다. (아래 그림 참조)

head가 current에 할당되며 current도 a를 가리킵니다. 

current의 current의 next 즉, a의 next가 할당되며 current는 b를 가리키게 됩니다. 

current의 current의 next 즉, b의 next가 할당되며 current는 c를 가리키게 됩니다. 

이때 c의 next는 NULL이므로 루프 문을 빠져나오게 됩니다. 

 

최종적으로 current 포인터가 list 변수들을 순회하며 num 멤버 변수를 정상적으로 출력한 것을 확인할 수 있었습니다. 

 

오늘은 구조체 포인터와 구조체 배열에 대해 정리해보았습니다!!

구조체에 대해 더 궁금하신 분들은 저번 포스팅도 참고해주세요~

2022.09.23 - [C언어] - C언어 - 구조체 (struct)

 

C언어 - 구조체 (struct)

안녕하세요 오늘은 구조체에 대해 알아보겠습니다~ 지금까지는 기본 자료형(int, double, char etc.)등으로만 코드를 구성했다면 오늘은 사용자 정의 자료형 즉, user의 필요에 따른 자료형을 struct를

leggo-fire.tistory.com

2022.09.24 - [C언어] - C언어 - 구조체 (struct) (2)

 

C언어 - 구조체 (struct) (2)

안녕하세요 저번 포스팅에 이어 구조체에 대해 더 정리해보겠습니다. 구조체의 활용 예제를 몇 가지 살펴볼 텐데요. 1. 배열 및 포인터를 구조체의 멤버 변수로 사용 2. 구조체를 구조체의 멤버

leggo-fire.tistory.com

그럼 다음에 만나요~

감사합니다. 좋은 하루 보내세요!!

Comments