c언어 - 구조체 포인터

구조체 포인터 선언 및 동적할당
struct 구조체이름 *포인터이름 = malloc(sizeof(struct 구조체이름));

구조체 별칭 포인터 선언
구조체별칭 *포인터이름 = malloc(sizeof(구조체별칭));

구조체 포인터에 구조체 변수의 주소 할당하기
구조체포인터 = &구조체변수;


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
43
44
45
// 구조체 정의
struct Person {
    char name[20];
    int age;
    char address[100];
};
 
// 구조체 포인터 선언, 메모리 할당
struct Person *p1 = malloc(sizeof(struct Person));
 
// 화살표 연산자
strcpy(p1->name, "홍길동");
p1->age = 30;
strcpy(p1->address, "서울시 용산구 한남동");
 
// 화살표 연산자
printf("이름: %s\n", p1->name);
printf("나이: %d\n", p1->age);
printf("주소: %s\n", p1->address);
 
 
//-----------------------------------------------
// typedef로 정의한 구조체 별칭
 
// 구조체 별칭 정의
typedef struct _Person {
    char name[20];
    int age;
    char address[100];
} Person;
 
// 구조체 별칭으로 포인터 선언, 메모리 할당
Person *p1 = malloc(sizeof(Person));
 
 
//-----------------------------------------------
// 익명 구조체
typedef struct {
    char name[20];
    int age;
    char address[100];
} Person;
 
// 구조체 별칭으로 포인터 선언, 메모리 할당
Person *p1 = malloc(sizeof(Person));
cs


출처 : c언어 코딩도장

댓글