Libft(4) - memccpy

2021. 5. 22. 20:5642seoul/42 Cursus

Libft(4) - memccpy

MEMCCPY(3)               BSD Library Functions Manual               MEMCCPY(3)

NAME
     memccpy -- copy string until character found

LIBRARY
     Standard C Library (libc, -lc)

SYNOPSIS
     #include <string.h>

     void *
     memccpy(void *restrict dst, const void *restrict src, int c, size_t n);

DESCRIPTION
     The memccpy() function copies bytes from string src to string dst.  If the character
     c (as converted to an unsigned char) occurs in the string src, the copy stops and a
     pointer to the byte after the copy of c in the string dst is returned.  Otherwise, n
     bytes are copied, and a NULL pointer is returned.

     The source and destination strings should not overlap, as the behavior is undefined.

SEE ALSO
     bcopy(3), memcpy(3), memmove(3), strcpy(3)

HISTORY
     The memccpy() function first appeared in 4.4BSD.

BSD                              June 9, 1993                              BSD

 

  • src에서 dst 로 복사.
  • unsigned char 로 바뀔 문자 c 가 src 안에 존재한다면 복사를 멈추고 dst 문자열에서 c 가 복사된 다음 바이트의 포인터를 리턴함.
  • c 가 src 안에 없다면 n 바이트가 복사되고 NULL 포인터가 리턴됨.
  • source, destination 문자열의 overlap은 정의되지 않음.

 

기본 함수 구조 및 매개변수

     #include <string.h>

     void *
     memccpy(void *restrict dst, const void *restrict src, int c, size_t n);
  • dst : 복사 받을 메모리를 가리키는 포인터.
  • src : 복사할 메모리를 가리키는 포인터.
  • c : src에서 만나면 복사를 중단할 데이터(unsigned char)
  • n : 복사할 데이터의 byte 수

 

리턴값

  • dest + 복사된 바이트 수
    • src에서 c가 있을 때
    • dest에서 복사가 끝난 데이터의 다음 메모리 주소
    • 추가 복사를 쉽게 하기 위한 리턴 값.
  • NULL
    • src에서 c 가 없을 때

 

+) 왜 c를 char 형이 아닌 int 형으로 받을까?

오늘날 c와 달리 예전에는 매개변수를 안에 안 적거나 적더라도 type을 적지 않는 prototype으로 작성했었음.

char *strchr();

char *strchr(s, c);

이런 방식 때문에 char로 이용된다고 해도 컴퓨터는 일단 int로 처리하고 함수 내부에서 char로 변환되는 방식이 사용됨.

c언어 하위 버전과의 호환성 때문에 이런 방식 계속 사용된 것.

참고 자료

https://www.it-note.kr/66

 

memccpy(3) - memory 영역간 데이터 복제(특정 문자까지)

memccpy(3) #include void *memccpy(void *dest, const void *src, int c, size_t n); memccpy(3)는 src 데이터를 n바이트의 데이터를 dest에 복제할 때에 src 데이터에서 문자 c를 만나면 c까지 복제하고 복제를..

www.it-note.kr

https://stackoverflow.com/questions/2394011/why-does-strchr-take-an-int-for-the-char-to-be-found

 

Why does strchr take an int for the char to be found?

The strchr function in the C standard library looks for a char in a string, but its signature takes an int for the search character. In these two implementations I found, the implementation casts ...

stackoverflow.com

 

'42seoul > 42 Cursus' 카테고리의 다른 글

Libft(6) - memchr  (0) 2021.06.26
Libft(5) - memmove  (0) 2021.06.26
Libft(3) - memcpy  (0) 2021.05.22
Libft(2) - bzero  (0) 2021.05.22
Libft(1) - memset  (0) 2021.05.22