본문 바로가기

Linux/C

[C] sizeof() vs strlen()

size_t strlen(const char *str)

 - 문자열의 길이를 반환한다. 이때 문자열의 마지막인 '/0'(null character)을 포함하지 않는다
 - <string.h>에 포함되어 있다.

size_t sizeof(const char *str)

 - 할당 된 버퍼의 크기를 반환한다.
 -<stdio.h>에 포함되어 있다.


  1. #include <stdio.h>  
  2. #include <string.h>  
  3. int main()  
  4. {  
  5.     char str[] = "Hello World!";  
  6.     printf("strlen() :%d\n",strlen(str));  
  7.     printf("sizeof() :%d\n"sizeof(str));  
  8.     return 0;  
  9. }  

결과는 아래와 같다. sizeof()가 13인것은 문자열의 끝인 '/0'을 포함한 버퍼의 크기이기 때문이다. 

strlen() :12
sizeof() :13

--------------------------------
Process exited after 0.00496 seconds with return value 0
계속하려면 아무 키나 누르십시오 . . .


한가지 더!

strlen( )의 시간 복잡도는 이므로 다음과 같은 코드는 의 시간 복잡도를 가지게 된다.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. int main()  
  4. {  
  5.     int i;  
  6.     char str[] = "This is test!";  
  7.     for (i = 0; i < strlen(str); i++)  
  8.         //Do something..  
  9.     return 0;  
  10. }  


따라서 다음과 같이 사용하는 것이 좋겠다.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. int main()  
  4. {  
  5.     int i,len;  
  6.     char str[] = "This is test!";  
  7.     len = srtlen(str);  
  8.     for (i = 0; i < len; i++)  
  9.         //Do something..  
  10.     return 0;  
  11. }  


'Linux > C' 카테고리의 다른 글

[c] size_t의 포멧형식  (0) 2018.01.31
[c] gets( ) vs scanf( )  (0) 2018.01.31