Advertisement
RicardasSim

strlen sizeof

Nov 28th, 2022
759
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.63 KB | None | 0 0
  1. //linux, 64bit, gcc, -Wall -Wextra -Wpedantic -Wshadow
  2.  
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6.  
  7. char a_str[] = "little weasel";
  8. char u_str[] = "žebenkštis";
  9.  
  10. char *p_str;
  11.  
  12. int main()
  13. {
  14.  
  15.     printf( "%s\n", a_str );
  16.     printf("Length of string a_str = %zu\n", strlen(a_str) );
  17.     printf("sizeof of a_str = %zu\n", sizeof a_str );
  18.     printf("sizeof of *a_str = %zu\n", sizeof *a_str );
  19.     printf("sizeof of a_str[0] = %zu\n\n", sizeof a_str[0] );
  20.  
  21.     printf( "%s\n", u_str );
  22.     printf("Length of string u_str = %zu\n", strlen(u_str) );
  23.     printf("sizeof of u_str = %zu\n", sizeof u_str );
  24.     printf("sizeof of *u_str = %zu\n", sizeof *u_str );
  25.     printf("sizeof of u_str[0] = %zu\n\n", sizeof u_str[0] );
  26.  
  27.     p_str = malloc( strlen(a_str) + 1 );
  28.  
  29.     if ( !p_str )
  30.     {
  31.         printf("Error: cannot allocate memory.\n");
  32.         return 1;
  33.     }
  34.  
  35.     // copies a_str, including the ending null character
  36.     strcpy( p_str, a_str );
  37.  
  38.     printf( "%s\n", p_str );
  39.     printf("Length of string p_str = %zu\n", strlen(p_str) );
  40.     printf("sizeof of p_str = %zu\n", sizeof p_str );
  41.     printf("sizeof of *p_str = %zu\n", sizeof *p_str );
  42.     printf("sizeof of p_str[0] = %zu\n\n", sizeof p_str[0] );
  43.  
  44.     free ( p_str );
  45.  
  46.     return 0;
  47. }
  48.  
  49. /*
  50. output:
  51.  
  52. little weasel
  53. Length of string a_str = 13
  54. sizeof of a_str = 14
  55. sizeof of *a_str = 1
  56. sizeof of a_str[0] = 1
  57.  
  58. žebenkštis
  59. Length of string u_str = 12
  60. sizeof of u_str = 13
  61. sizeof of *u_str = 1
  62. sizeof of u_str[0] = 1
  63.  
  64. little weasel
  65. Length of string p_str = 13
  66. sizeof of p_str = 8
  67. sizeof of *p_str = 1
  68. sizeof of p_str[0] = 1
  69.  
  70. */
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement