자료구조(C)/배열,구조체,포인터

3.4 구조체와 포인터

CMS419 2020. 7. 17. 11:58

구조체에 대한 포인터를 선언하고 포인터를 통하여 구조체 멤버에 접근할 수 있다.

표기법은 "->"이다. ps가 구조체를 가리키는 포인터라 할 때, (*ps).i 보다는 ps->i라고 쓰는 것이 더 편리하다.

자료 구조에서 구조체에 대한 포인터도 자주 함수의 매개변수로 전달된다.

 

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

typedef struct studenTag {
char name[10];
int age;
double gpa;
} student;

int main() {
student *s;

s = (student *)malloc(sizeof(student));
if (s == NULL) {
fprintf(stderr, "메모리가 부족해서 할당할 수 없습니다.");
exit(1);
}

strcpy_s(s->name, "Park");
s->age = 20;

printf("%d\n%s\n", s->age, s->name);

free(s);
return 0;
}

 

s->name이 (*s).name로 할 수 있습니다. 그렇지만 s->name이 더 편리하다.