본문 바로가기
학습/IT

[IT] C언어 입문(12) structure, union, enumerated types - 구조체, 공용체, 열거체

by 개성공장 2021. 9. 11.
반응형

□ structure / union / enumerated types

 

 * Arguments to main()

 - To communicate with the OS

 - argc: the number of command line arguments   // argc, argy 변수의 이름은 관례이므로 바꿔도 오류는 안 남

 - argv: an array of strings

 - The strings are the words that make up the command line

 - argv[0] contains the name of the command itself

 - 사용자가 인자를 프로그램에 직접 주기 위해 사용, 명령 프롬프트!

 

---

#include<stdio.h>
int main(int argc, char *argv[])
{
	int i;
	printf("argc = %d\n", argc);
	for (i=0; i<argc; i++)
		printf("argv[%d] = %s\n", i, argv[i]);
	return 0;
}

---

 

string을 array로 표현할 때... => string이 곧 배열이므로, 다차원 배열

 * Ragged Arrays

 - An array of pointers whose elements are used to point to arrays of varying sizes.

 

 - char x[2][7] = { "abc", "abcde" };

 => x  | a b c \0    NULL ...

          a b c d e \0  NULL ...

 

 - char *p[2] = {"abc", "abcde"};    // 더 많은 데이터 공간을 아낄 수 있음

 => p | ㅁ   <- "a b c \0"

         ㅁ   <- "a b c d e \0"

 

□ file operation

 * File and File Pointers

 - A file is a stream of characters or bits

 - The identifier FILE defined in 'stdio.h' is a structure that describes the current state of a file

 - Three file pointers defined in 'stdio.h'

 - stdin : standard input file (keyboard)

 - stdout : standard output file (screen)

 - stderr : standard error file (screen)

 

 - File versions of printf and scanf

 - fprintf ( file_ptr, control_string, other_arguments );    // fprintf( stdout, ) => printf( )

 - fscanf ( file_ptr, control_string, other_arguments )l    // fscanf( stdin ) => scanf( )

 - fputc, fgetc ...

 

 * fopen() and fclose()

 - for reading, writing, and appending to a file

 

 

#include<stdio.h>
int main(void)
{
	int a, sum=0;
	FILE *ifp, *ofp;

	ifp = fopen("infile", "r");
	ofp = fopen("outfile", "w");
	...
	fclose(ifp);
	fclose(ofp);
}

"r" : open text file for reading

"w" : for writing

"a" : for appending

"rb" : open binary file for reading

"wb", "ab"

"r+" : open text file for reading and writing

"w+" : open text file for writing and reading

 

 

 * example

---

#include <stdio.h>
#include <stdlib.h>
void foo(FILE*, FILE*);
void print_msg(char *);

void print_msg(char *s)
{
	printf("\n%s%s%s%s\n", "usage :  ", s, "   infile", "   outfile");
}

int main(int argc, char **argv) {
	FILE *ifp, *ofp;
	if (argc != 3) {
		print_msg(argv[0]);
		exit(1);
	}
	ifp = fopen(argv[1], "r");
	ofp = fopen(argv[2], "w");
	foo(ifp, ofp);
	fclose(ifp);
	fclose(ofp);
	return 0;
}

---

 

 

□ Structures and Unions

 * Structures

 - To aggregate variables of different types

 - structure_declaration ::= struct_specifier declaration_list;

 - struct_specific ::= struct tag_name | struct { tag_name }opt  { { member_declaration }* };

 - tag_name ::= identifier

 - member_declaration ::= type_specifier declartion_list;

 - declaration_list ::= declarator { , declarator }*

 

밑의 4가지 표현 모두 동일

---

struct {
	int day, month, year;
	char day_name[4];
	char month_name[4];
} d1, d2, d3

---

struct date {                          //struct의 이름을 'date'로 선언
	int day, month, year;
	char day_name[4];
	char month_name[4];
};

struct date d1, d2, d3;

---

struct date {
	int day, month, year;
	char day_name[4];
	char month_name[4];
};

typedef struct date date;     // struct date를 date라는 type으로 정의
date d1, d2, d3;              // date type의 d1, d2, d3 선언

---

typedef struct {
	int day, month, year;
	char day_name[4];
	char month_name[4];
} date;                            // struct를 date로(type으로) 정의

date d1, d2, d3;

---

 

 

 * Accessing Members

struct {
	int day, month, year;
	char day_name[4];
	char month_name[4];
} d1, d2, d3;
...
x = d1.day     // structure 안의 개별 변수에 접근
d2.year = 2007;
d3.month_name[0] = 'm';
d3.month_name[1] = 'a';
d3.month_name[2] = 'y';
d3.month_name[2] = '\0';

---

// pointer_to_structure  -> member_name
// ( * pointer_to_structure ) . member_name

struct date {
	int day, month, year;
	char day_name[4];
	char month_name[4];
};
struct date d1, d2, d3;
struct date *d;

d = &d1;
d->year = 2007;    // 가독성이 좋은 방법. d라는 struct에서 year라는 멤버를 찾아 2007을 입력
(*d).month = 11;

 

 * Initializing Structures

typedef struct {
	float re;
	float im;
} complex;

complex a;
complex x[2][2] = { {{ 0.0, 0.0 }, { 3.0, 2.1 }}, {{ -0.3, 2.1 }, { 5.0, 3.4 }} };
※ C언어 입문 시리즈
1. Introduction - C언어의 역사와 기본 개념
2. Variables - 변수, 대입연산자, 구문규칙, 데이터타입 등
3. Data types, 데이터 타입(자료형)
4. Operators, 연산자 - scanf, 산술연산자, 관계연산자, 증감연산자, 대입연산자, 동등연산자 등
5. Operators, 연산자 - 논리연산자, 단축평가, 대입연산자, if문 및 while문 활용
6. Control flow, 제어흐름 - While문, For문, If문, do-while문 등 루프문
7. Function, 함수 - Goto문, getchar와 putchar, 함수 정의와 프로토타입 선언
8. Scope rules/recursion, 변수의 영역규칙과 재귀호출, 난수생성 예시
9. Array와 Pointers, 배열과 포인터
10. Pointer, 역참조, swap 함수 활용, 배열과 포인터 비교
11. File operation 파일연산, String, 다차원 배열 예시
12. structure, union, enumerated types - 구조체, 공용체, 열거체
13. 자료구조(data structure) 예시 - 연결리스트(linked list)
14. C 전처리기(C preprocessor), 함수 포인터(function pointer)
반응형

댓글