본문 바로가기
학습/IT

[IT] C언어 입문(11) File operation 파일연산, String, 다차원 배열 예시

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

□ file operations

 

 * calloc() and malloc() 함수 => 동적 메모리 할당

 - In the standard library (stdlib.h)

 - To dynamically create storage for arrays, structures, and unions

 

 - void* calloc( size_t n, size_t s )

 - Contiguous allocation : Allocates contiguous space in memory with a size of n * s bytes

 - The space is initialized with 0%

 - If successful, returns a pointer to the base if the space

 - Otherwise, returns NULL

 - Typically "typedef unsigned int size_t;" in stdlib.h

x = calloc( n, sizeof(int) );

 

 - void* malloc( size_t s );

 - similar to calloc()

 - Allocates contiguous space in memory with a size of s bytes without initialization

x = malloc( n * sizeof(int) );

 

---

int main(void)
{
	int n;
	int *p = NULL;

	scanf("%d", &n);
	if((p = (int *) malloc( sizeof(int) * n )) == NULL )
	{
		printf("allocation error\n");
		exit(0);
	{
}

---

 

 - The programmer should explicitly return the space

 - free(ptr);

 - Makes the space in memory pointer by 'ptr' to be deallocated

 - 'pt' must be the base address of space previously allocated

 

 

□ String, 다차원 배열

 * Two-dimensional Arrays

int x[3][4];         // 세로 3, 가로 4, 4개짜리 배열이 3층으로 있는 것

x[i][j] = * (& x[0][0] + 4*i + j)

---

int sum(int x[][4])       // int x[3][] 의 경우에는 컴파일 오류
{
	int i, j, sum=0;
	for (i=0; i<j; i++)                 // for루프 중첩
		for(j=0; j<4; j++)
			sum += x[i][j];
	return sum;
}

---

 

 * Three dimensional Arrays 도 있다

 

 * Initialization of Multidimensional Arrays

 - An array of storage class automatic is not explicitly initialized

 - All static and external arrays are initialized to zero by default

예제

int x[2][3] = { 1, 2, 3, 4, 5, 6};
int x[2][3] = { {1, 2, 3}, {1, 2, 3}};
int x[][3] = { {1, 2, 3}, {1, 2, 3}};
int x[2][2][3] = {{{1,1,0}, {2,0,0}}, {{3,0,0}, {4,0,0}}};
int x[2][2][3] = { 0 };

 

 

 * Strings

 - Strings are one dimensional arrays of type char

 - A string in C is terminated by the null character '\0' (end-of-string sentinel)

 - The size of a string must include '\0'

 

 - String constants are written between double quotes

 - Treated as a pointer

 - The value is the base address of the string

char *p = "abc";
printf("%s, %s\n", p, p+1);   // 'abc, bc' 출력
"abc"[2]   // 'c'
* ("abc" + 2)   // 'c'
char s[] = "abc";
char s[] = { 'a', 'b', 'c', '\0' };

 

 

 * Counting the Number of Words in a String 예제

#include<ctype.h>
	int wordCount(const char *s)
	{
	int cnt = 0;
	while (*s != '\0') {            // string의 끝에 도달하지 않은 동작 작업 반복
		while (isspace(*s)) {   // 인자로 주어진 값이 스페이스(공백, 탭 ... 등 white space)인지 확인 
			s++;
		}
		if(*s != '\0') {        // string이 스페이스로만 이뤄지는 경우 오류를 방지
			cnt++;
			while ( !isspace(*s) && *s != '\0')
				s++;
		}
	}
	return cnt;
}

---

 

 * String-Handling Functions (stdlib.h)

 - char *strcat(char *s1, const char *s2);

 - Concatenates two strings s1 and s2 and puts the result in s1

 

 - int strsmp(const char *s1, const char *s2);

 - An integer is returned that is less than equal to, or greater than zero, depending on whether s1 is lexicographically less than, equal to, or greater than s2.

 

 - char *strcpy(char *s1, const char *s2);

 - The characters in s2 are copied into s1 until '\0' is moved

 - The pointer s1 is returned

 

 - size_t strlen(const char *s);

 - A count of the number of characters before '\0' is returned

 

strlen()

---

size_t strlen(const char *s)
{
	size_t n;

	for ( n=0; *s != '\0'; ++s )
		++n;

	return n;
}

---

 

strcpy()

---

char *strcpy(char *s1, register const char *s2)
{
	register char *p = s1;
	while(*p++ = *s2++)

	return s1;
}

---

 

strcat

---

char *strcat(char *s1, register const char *s2)
{
	register char *p = s1;

	while(*p)
		++p;
	while(*p++ = *s2++)

	return s1;
}
※ 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)
반응형

댓글