Guest User

Untitled

a guest
May 27th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. ```c
  2. #include <stdio.h>
  3. #include <string.h>
  4. int main()
  5. {
  6. char * ptr = "123456789";
  7. printf("strlen_ptr: %lu\n", strlen(ptr));
  8. printf("sizeof_ptr: %lu\n", sizeof(ptr));
  9.  
  10. char arr[20] = "123456789";
  11. printf("strlen_arr: %lu\n", strlen(arr));
  12. printf("sizeof_arr: %lu\n", sizeof(arr));
  13.  
  14. printf("strlen_str: %lu\n", strlen("woshizifuchuan"));
  15. printf("sizeof_str: %lu\n", sizeof("woshizifuchuan"));
  16.  
  17. }
  18.  
  19. ```
  20. 结果
  21. ```text
  22. strlen_ptr: 9
  23. sizeof_ptr: 8
  24.  
  25. strlen_arr: 9
  26. sizeof_arr: 20
  27.  
  28. strlen_str: 14
  29. sizeof_str: 15
  30. ```
  31.  
  32. 最近维护一个程序,发现代码里面总是会对 `char *` 混用 `strlen` 和 `sizeof`
  33.  
  34. 但是可以正常运行, 这里测试一下。。
  35.  
  36. #### `strlen`
  37.  
  38. 都是取字符串的真实长度,
  39.  
  40. #### `sizeof`
  41.  
  42. 1. 字符串数组的时候 `sizeof` 取分配的数组的大小
  43. 2. 字符串指针的话取得是 `char` 的长度,
  44. 3. 字符串常量的话是字符串分配的长度包含最后的`\0`符号。所以会经常看到 `sizeof("str") - 1` 这种写法
  45.  
  46. 也就是当字符串指针的时候长度不超过 `char` 的长度的话,分配出来内存够用,于是不会报错。。。
Add Comment
Please, Sign In to add comment