어제 이어서.

Implement strcat() function in C | Techie Delight

해당 링크에서 가져온 strcat()함수 코드

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
 
// Function to implement `strcat()` function in C
char* my_strcat(char* destination, const char* source)
{
    // make `ptr` point to the end of the destination string
    char* ptr = destination + strlen(destination);
 
    // appends characters of the source to the destination string
    while (*source != '\\0') {
        *ptr++ = *source++;
    }
 
    // null terminate destination string
    *ptr = '\\0';
 
    // the destination is returned by standard `strcat()`
    return destination;
}
 
// Implement `strcat()` function in C
int main()
{
    char* str = (char*)calloc(100, 1);
 
    my_strcat(str, "Techie ");
    my_strcat(str, "Delight ");
    my_strcat(str, "– ");
    my_strcat(str, "Ace ");
    my_strcat(str, "the ");
    my_strcat(str, "Technical ");
    my_strcat(str, "Interviews");
 
    puts(str);
 
    return 0;
}

홍정모님은 이런 표준 함수들을 구현해보는 일이 매우 중요하다고 함. 실무에서는 이런 함수를 가져다 쓰기만 하기 때문에 공부하는 단계에서만 할 수 있다고 함. 자주 이런 기회를 접하면서 함수의 구조를 파악해보라.

위 함수에서 핵심 아이디어는 포인터를 하나 새로 만들되, 우리가 조작하고 싶은 주소를 가리키는 실제의 포인터를 하나 만드는 것임. 이 포인터는

char* ptr = destination + strlen(destination);

를 통해 만들어진다.

그리고 while()문 마지막 증가된 ptr\\0을 넣어줌으로써 append된 결과가 문자열처럼 인식되게 만듦

다음으로는 strcmp()strncmp()라는 함수이다.

여기서 cmp는 compare를 의미함.(비교) 다만 characters 비교가 아니라 문자열 비교임.

이 둘은 반환값이 특이함. 비교해서 같으면 0을 반환함.

그리고 비교해서 다르면 다른 정수를 반환하는데, 이때는 문자열의 순서, 아스키코드에 따라 다른 정수를 반환한다. 예제를 통해 확인해보자.

printf("%d\\n", strcmp("A", "A"));
printf("%d\\n", strcmp("A", "B"));
printf("%d\\n", strcmp("B", "A"));
printf("%d\\n", strcmp("Hello", "Hello"));
printf("%d\\n", strcmp("Banana", "Bananas"));
printf("%d\\n", strcmp("Bananas", "Banana"));
printf("%d\\n", strcmp("Bananas", "Banana", 6));

위 코드의 실행 결과이다.

Untitled