C언어 strlen 함수 구현하기

strlen()은 문자열의 널 종료 문자가 나오기 전까지 문자 수를 센다. 널 종료 문자는 길이에 포함하지 않는다.




#include <stdio.h>
#include <stddef.h>

size_t my_strlen(const char *text) {
    size_t count = 0;
    while (text[count] != 0) ++count;
    return count;
}

int main(void) {
    const char fruit[] = "Strawberry";
    printf("%zu\n", my_strlen(fruit));
}




문자열은 반드시 널 종료되어 있어야 한다. 종료 문자가 없는 버퍼에 적용하면 범위를 넘어 읽게 된다.

Comments

댓글을 불러오고 있습니다.