Structure

Lecture PPT

For Embedded Controller


Online Lesson

코딩도장 핵심요약: 구조체 사용하기 핵심요약

We can define our own data type of a set of related field members.

Each field member can be defined with a different data type.

Structure declaration and definition

  • Structure variables, Tagged structures, Type-defined structures

Example Code

Example 1

C_structure_example.c

Example 2

구조체 변수 d1의 멤버 numPtr을 역참조 하는 방법과 구조체 포인터 d2의 멤버 numPtr을 역참조 하는 방법을 그림으로 표현하면 다음과 같은 모양이 됩니다.

구조체 멤버가 포인터일 때 역참조하기

fig. 49-1

만약 역참조한 것을 괄호로 묶으면 어떻게 될까요? 이렇게 하면 구조체 변수를 역참조한 뒤 멤버에 접근한다는 뜻이 됩니다. *(*d2).numPtr처럼 구조체 포인터를 역참조하여 numPtr에 접근한 뒤 다시 역참조할 수도 있습니다.

(*구조체포인터).멤버

*(*구조체포인터).멤버

여기서

(*d2).c1 는 d2->c1 같고

*(*d2).numPtr 는 *d2->numPtr 과 같습니다.

즉, 구조체 포인터를 역참조한 뒤 괄호로 묶으면 -> 연산자에서 . 연산자를 사용하게 되므로 포인터가 일반 변수로 바뀐다는 뜻입니다. 역참조의 원리와 같죠.

fig. 49-2

Example 3

구조체 별칭으로 선언한 포인터도 구조체 멤버에 접근할 때는 -> (화살표 연산자)를 사용합니다. p1->age = 30;

struct 키워드로 포인터를 선언하고 메모리를 할당했으니 typedef로 정의한 구조체 별칭으로도 포인터를 선언하고 메모리를 할당할 수 있겠죠?

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

Example 4

지금까지 malloc 함수로 구조체 포인터에 동적 메모리를 할당했습니다. 그럼 동적 메모리를 할당하지 않고 구조체 포인터를 사용하는 방법은 없을까요? 이때는 구조체 변수에 & (주소 연산자)를 사용하면 됩니다.

구조체포인터 = &구조체변수;

ptr에 p1의 메모리 주소를 할당했으므로 ptr의 멤버를 수정하면 결국 p1의 멤버도 바뀝니다. 접근하는 방식만 차이가 있을 뿐 결국 같은 곳의 내용을 수정하게 됩니다(메모리 주소는 컴퓨터마다, 실행할 때마다 달라집니다).

구조체 변수의 주소와 구조체 포인터

Example 5: Structure in a Structure

Structure within Structure is a Useful technique for embedded programming (especially using FSM)


Exercise

Exercise 1

C_structure_exercise.c

Fill in the code to get the output of

  • 이름: 고길동

  • 학년: 1 반: 3

  • 평균점수: 65.389999

Check answer here

Exercise_1 result

Exercise 2

C_structure_exercise2.c

Define a structure member as

  • Typedef Struct Handong

  • Members: char building_name[100], int room_number, char room_name[100];

C_structure_exercise2.c

Create structure variables room1, room2, room3. Assign the member values as

Building name

Room number

Room name

room1

Newton

109

iiLAB

room2

Newton

118

Control-Lab

room3

Newton

119

SW-Lab

Create roomPt as Pointer variable of Handong type

Print each room names as follows

image

Exercise 3

C_structure_exercise3.c

  • Define a structure member for 3D position

  • Create the following functions

Use your functions in Main() as

Exercise_2 result

Last updated

Was this helpful?