구조체 변수를 일일이 선언해서 사용하는 것보다는 포인터에 메모리에 할당 당해서 사용한다.
중첩 구조체 : 구조체 내에 구조체가 멤버로 포함 구조체
#include <stdio.h>
typedef struct _score
{
float math;
float eng;
float total;
float avg;
}SCORE;
typedef struct _stu
{
int no;
SCORE s;
}STUDENT;
int main(void)
{
}
구조체 배열
배열의 요소가 될 수 있는 타입에는 제한이 없다.
따라서 구조체도 배열의 요소가 될 수 있으며 구조체 배열을 정의하는 것이 가능.
#include <stdio.h>
typedef struct _student{
char no[10];
char name[20];
float math;
}student;
}student;
int main(void)
{
student st[3];
for(int i=0; i<3; i++){
printf("학번, 이름, 수학 점수 순으로 입력\n");
scanf("%s %s %f", st[i].no, st[i].name, st[i].math);
}
printf("\n");
for(int i = 0; i < 3; i++)
{
printf("%s %s %f\n", stu[i].no, stu[i].name, stu[i].math);
}
return 0;
}
멤버 변수로 포인터 변수 사용
구조체 멤버 변수로 포인터 변수 역시 사용가능 하다.
#include <stdio.h>
typedef struct _point
{
int *x;
int** y;
int** z;
}point;
int main(void)
{
int num = 3;
int temp = 4;
point pt;
pt.x = #
pt.y = &pt.x;
pt.z = &temp;
printf("%d %d %d %d\n", num, *pt.x, **pt.y, *pt.z);
return 0;
}
구조체 포인터
구조체 별 * 포인터 이름 = malloc(sizeof(struct 구조체 이름));
구조체를패킷으로 사용한다면 일반적으로 STX, CMD , LEN , DATA , 에러 체크(ERROR CODE) ETX 구조로 이루어진다.
#include <stdio.h>
typedef struct student
{
char dob[10];
char name[20];
double height;
} STUDENT;
int main(void)
{
STUDENT stu = {"20050121", "박효원", 170};
STUDENT* p1 = NULL;
p1 = &stu;
printf("%s %s %lf\n", stu.dob, stu.name, stu.height);
printf("%s %s %lf\n", (*p1).dob, (*p1).name, (*p1).height);
printf("%s %s %lf\n", p1->dob, p1->name, p1->height);
return 0;
}
구조체 포인터 배열
사용 방법
- struct 구조체이름 *포인터이름[배열 크기]
예제
아래처럼 어떤 MCU 레지스터 목록을 구조체로 정의하고, 이를 포인터 배열로 선언하여, 동일한 구조체 배열들을 사용할수 있다.
typedef struct
{
__IO uint32_t SCI_DATA;
__IO uint32_t SCI_CR0;
__IO uint32_t SCI_CR1;
__IO uint32_t SCI_CR2;
__IO uint32_t SCI_IER;
__IO uint32_t SCI_RETRY;
__IO uint32_t SCI_TIDE;
__IO uint32_t SCI_TXCOUNT;
__IO uint32_t SCI_RXCOUNT;
__I uint32_t SCI_FR;
__IO uint32_t SCI_RXTIME;
__IO uint32_t SCI_ISTAT;
__IO uint32_t SCI_STABLE;
__IO uint32_t SCI_ATIME;
__IO uint32_t SCI_DTIME;
__IO uint32_t SCI_ATRSTIME;
__IO uint32_t SCI_ATRDTIME;
__IO uint32_t SCI_BLKTIME;
__IO uint32_t SCI_CHTIME;
__IO uint32_t SCI_CLKICC;
__IO uint32_t SCI_BAUD;
__IO uint32_t SCI_VALUE;
__IO uint32_t SCI_CHGUARD;
__IO uint32_t SCI_BLKGUARD;
__IO uint32_t SCI_SYNCCR;
__IO uint32_t SCI_SYNCDATA;
__IO uint32_t SCI_RAWSTAT;
__IO uint32_t SCI_IIR;
__I uint32_t SCI_RES1[4];
__I uint32_t SCI_RES2[32];
} SCI_TypeDef;
static SCI_TypeDef * const aSCI_BaseTable[3] = {(SCI_TypeDef *)SCI0_BASE, (SCI_TypeDef *)SCI1_BASE, (SCI_TypeDef *)SCI2_BASE};
구조체의 멤버가 포인터일 때 역참조하기
구조체 포인터에 구조체 변수의 주소 할당하기
구조체 포인터 = &포인터변수;
[선형구조]자료 구조의 개념 정리(리스트, 스택, 큐, 데크) :: 개발/일상_Mr.lee (tistory.com)
10-03. 구조체와 배열 - C 언어 (wikidocs.net)
'프로그래밍 언어 > c(일반)' 카테고리의 다른 글
| [펌]RFID/NFC[3] (3) | 2024.11.27 |
|---|---|
| do ~ while문 , goto문 (0) | 2024.07.26 |
| BCD <-> DCB (0) | 2024.07.18 |
| 포인터(5) - 다중 포인터(이중포인터 위주) (0) | 2024.07.12 |
| 포인터(4) - 함수 포인터 & 사용 예시 정리 (0) | 2024.07.12 |