strcpy 사용법 및 구현 - C 문자열 복사
사용법
#include <string.h>
char *strcpy(char *dest, const char *src);
char *strncpy(char *dest, const char *src, size_t n);
정의 (strcpy strncpy 차이점)
strcpy() 함수는 null byte 를 포함하는 src 문자열을 dest 버퍼에 복사합니다.
dest 와 src 의 메모리는 겹치지(오버랩)않아야 합니다. 그리고 dest 버퍼는 src문자열을
복사하기에 충분한 사이즈여야 합니다.
strncpy() 함수는 src 문자열을 n byte만큼 복사하는것을 제외하면 strcpy() 함수와 같습니다.
주의 : 만약 src 문자열에서 n byte 사이즈 안에 null byte 가 없다면 dest 문자열에도 null byte가
추가되지 않으므로 정상적인 문자열 처리가 불가능해지므로 주의하시기 바랍니다.
(아시다시피 문자열의 끝은 null byte로 구분하기 때문에)
그리고 str 의 문자열 크기가 n byte보다 작다면 strncpy() 함수는 dest 함수의 마지막에 추가로 n
byte 만큼 null byte 로 모두 초기화 합니다.
반환 값
strcpy()와 strncpy() 함수 모두 dest 의 포인터를 반환합니다.
strcpy() 와 strncpy() 구현 (실제 구현부)
/**
* strcpy - Copy a %NUL terminated string
* @dest: Where to copy the string to
* @src: Where to copy the string from
*/
char *strcpy(char *dest, const char *src)
{
char *tmp = dest;
/*
* src 가 null byte 일때까지 dest에 한자씩 복사한 후 리턴합니다.
*/
while ((*dest++ = *src++) != '\0')
/* nothing */;
return tmp;
}
/**
* strncpy - Copy a length-limited, C-string
* @dest: Where to copy the string to
* @src: Where to copy the string from
* @count: The maximum number of bytes to copy
*
* The result is not %NUL-terminated if the source exceeds
* @count bytes.
*
* In the case where the length of @src is less than that of
* count, the remainder of @dest will be padded with %NUL.
*
*/
char *strncpy(char *dest, const char *src, size_t count)
{
char *tmp = dest;
while (count) {
/*
* src 가 null byte 일때까지 dest에 복사하고,
* 그 이후에는 src 값(현재 null byte)을 증가하지 않고 count 만큼
* dest 에 복사하므로 나머지 데이터가 count 만큼
* null byte 로 모두 초기화됩니다.
*/
if ((*tmp = *src) != 0)
src++;
tmp++;
count--;
}
return dest;
}
strcpy() 함수는 src 문자 한자씩 null byte 까지 dest 에 복사합니다.
strncpy() 함수는 src 문자 한자씩 null byte 까지 dest 에 복사한 후, 그 이후는
현재 src 문자를(null byte) 남은 카운트 만큼 dest 에 복사합니다.
예를 들어 char src[5] = "ab" 이고 char dest[5] = "cccc"; 이고
strncpy(dest, src, sizeof(src)); 을 실행하면 dest 의 메모리는 아래와 같이 복사됩니다.
dest 의 메모리에 "ab"를 복사하고 나서 그 뒤에 메모리값은 원래 있던 'c' 문자열이
사라지고 sizeof(src) 만큼 null 로 채워집니다.
0x0000 | 0x0001 | 0x0002 | 0x0003 | 0x0004 |
a | b | null | null | null |
예제
#include <string.h>
#include <stdio.h>
int main(void)
{
char src[32] = "Source string";
char dest[32] = "Destination string";
/* src 문자열을 dest 로 복사합니다. */
strcpy(dest, src);
printf( "After strcpy, Destination is \"%s\"\n", dest);
return 0;
}
결과값은
After strcpy, Destination is "Source string"
입니다.