문타쿠, 공부하다.
[C언어 코딩 도장] Unit 42. 문자열을 복사하고 붙이기 본문
42.1 문자열 복사하기
문자열은 다른 배열이나 포인터(메모리)로 복사할 수 있다.
-> strcpy 함수를 사용하며 string.h 헤더 파일에 선언되어 있다.
1) 문자 배열을 사용하여 문자열 복사하기
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
int main(void)
{
char s1[10] = "Hello";
char s2[20];
strcpy(s2, s1);
printf("%s\n", s2);
return 0;
}
2) 문자열 포인터를 사용하여 문자열 복사하기
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
int main(void)
{
char* s1 = "Hello";
char* s2 = "";
strcpy(s2, s1);
printf("%s\n", s2);
return 0;
}
위의 코드는 '1) 문자 배열을 사용하여 문자열 복사하기'에서 사용한 방법을 문자열 포인터에 적용한 코드이다.
그런데 실행해보면 에러가 발생하는데, 이는 s2에 저장된 메모리 주소는 복사할 공간도 없을뿐더러, 읽기만 할 수 있지 쓰기는 불가능하기 때문이다.
이를 해결하기 위해선 즉, 문자열 포인터에 문자열을 복사하려면 문자열이 들어갈 공간을 따로 마련해야 하는데 아래와 같이 malloc 함수로 메모리를 할당한 뒤 문자열을 복사하면 된다.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char* s1 = "Hello";
char* s2 = malloc(sizeof(char) * 10);
strcpy(s2, s1);
printf("%s\n", s2);
free(s2);
return 0;
}
42.2 문자열 붙이기
문자열은 strcat 함수를 사용하여 서로 붙일 수 있으며 마찬가지로 string.h 헤더 파일에 선언되어 있다.
1) 문자 배열을 사용하여 문자열 붙이기
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
int main(void)
{
char s1[10] = "world";
char s2[20] = "Hello";
strcat(s2, s1);
printf("%s\n", s2);
return 0;
}
2) 문자열 포인터를 사용하여 문자열 붙이기
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
int main(void)
{
char* s1 = "world";
char* s2 = "Hello";
strcat(s2, s1);
printf("%s\n", s2);
return 0;
}
위의 코드는 '1) 문자 배열을 사용하여 문자열 붙이기'에서 사용한 방법을 문자열 포인터에 적용한 코드이다.
그런데 실행해보면 에러가 발생하는데, 복사하기와 마찬가지로 문자열 포인터 s2는 읽기 전용 메모리라서 문자열을 붙일 수 없다.
이를 해결하기 위해선 즉, 문자열 포인터에 문자열을 붙이려면 아래와 같이 malloc 함수로 동적 메모리를 할당한 뒤 문자열을 붙이면 된다.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char* s1 = "world";
char* s2 = malloc(sizeof(char) * 20);
strcpy(s2, "Hello");
strcat(s2, s1);
printf("%s\n", s2);
free(s2);
return 0;
}
42.3 배열 형태의 문자열을 문자열 포인터에 복사하기
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char s1[10] = "Hello";
char* s2 = malloc(sizeof(char) * 10);
strcpy(s2, s1);
printf("%s\n", s2);
free(s2);
return 0;
}
42.4 배열 형태의 문자열을 문자열 포인터에 붙이기
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char s1[10] = "world";
char* s2 = malloc(sizeof(char) * 20);
strcpy(s2, "Hello");
strcat(s2, s1);
printf("%s\n", s2);
free(s2);
return 0;
}
'C언어 > C언어 코딩 도장' 카테고리의 다른 글
[C언어 코딩 도장] Unit 43. 문자열 만들기 (0) | 2023.10.02 |
---|---|
[C언어 코딩 도장] Unit 42. 연습문제 및 심사문제 (0) | 2023.09.25 |
[C언어 코딩 도장] Unit 41. 연습문제 및 심사문제 (0) | 2023.09.25 |
[C언어 코딩 도장] Unit 41. 문자열의 길이를 구하고 비교하기 (0) | 2023.09.25 |
[C언어 코딩 도장] Unit 40. 연습문제 및 심사문제 (0) | 2023.09.24 |