4.4 strlen() 함수

공기훈·2021년 7월 22일
0

홍정모의 따배씨

목록 보기
8/49
#include <stdio.h>
#include <string.h> // strlen 을 사용하기 위해 include

int main()
{
	char str1[100] = "Hello";
	char str2[] = "Hello"; // 글자 수에 맞게 공간을 할당해준다.
	char str3[100] = "\0"; //빈칸과 \0은 다르다!
	char str4[100] = "\n";

	printf("%zu %zu\n", sizeof(str1), strlen(str1)); // 100 5 
	printf("%zu %zu\n", sizeof(str2), strlen(str2)); // 6 5
	printf("%zu %zu\n", sizeof(str3), strlen(str3)); // 100 0
	printf("%zu %zu\n", sizeof(str4), strlen(str4)); // 100 1

strlen 함수의 특징

함수를 사용하기 위해서는 <string.h> 파일을 include 해줘야 한다.
strlen은 인간에게 의미 있는 것만 세어준다.
\0은 count 되지 않는다.

	/* Extra */
	char* str5 = (char*)malloc(sizeof(char) * 100);
	str5[0] = 'h'; str5[1] = 'e'; str5[2] = 'l'; str5[3] = 'l'; str5[4] = 'o';
	str5[5] = '\0';
	printf("%zu %zu\n", sizeof(str5), strlen(str5)); // 4 5 출력
	return 0;
}

동적할당

동적 할당을 할 경우, 위의 예제처럼 편하게 불가능.
4 byte는 포인터 변수 자체의 사이즈.
str1[100] 과 같은 경우는, 해당 사이즈가 100byte인 것을 알고 있기 때문에 100이라고 출력이 되지만, char* str5는 메모리를 얼마나 많이 할당 받는지를 알 수가 없다.
그러므로 포인터 변수 주소를 적는 메모지의 사이즈만 알 수 있다.

profile
be a coding master

0개의 댓글