当前位置:网站首页>Common mistakes in C language (sizeof and strlen)

Common mistakes in C language (sizeof and strlen)

2022-06-23 01:49:00 Nobaya

      One 、sizeof and strlen The difference between

        sizeof yes C A key word in a language , and strlen It's a library function ( Included in <string.h> in ), The functions of the two seem very similar , however , It makes a big difference .

  •         strlen( Can only ) Is used to measure the length of a string ( It does not include the... That marks the end of the string ‘’).
  •          and sizeof Is to calculate an object ( It can be a variable or a data type ) Size in space , That is, the size of the occupied space .

                About strlen You can refer to the information here :   strlen A detailed description

         Two 、sizeof and strlen Application scenarios of

        First of all, let's look at a topic .

int num[20] = { 1 , 2, 3, 4, 5, 6, 7, 8, 9, 10 };char arr[50] = "abcdefg001";     seek arr The length and size of the space .     seek num Number of elements and size of space .

        Think about this topic is not very simple .

        


        Ask for in this topic num The number of elements can be used sizeof(num) / sizeof(num[0])  To get , Now sizeof(num) Represents the total space occupied by this array ( That is, the length of the data type * Element number ), and sizeof(num[0]) Represents the space occupied by the data type of this array . Let's take a look at the answer :

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA6Ku-5ZSE5Lqe,size_20,color_FFFFFF,t_70,g_se,x_16

        You can see :

  •         strlen In use, only '' Preceding characters . That's the number of characters .
  •         sizeof When used, it calculates how much space this object occupies in memory .

        


        matters needing attention :

  • Although the use of sizeof  You can find the number of elements of an array , But you can't use it across functions , Because an array will only pass The first address of the array Transfer the past . In this way, you can use   sizeof(num) / sizeof(num[0])   Will only get 1.
  • strlen  Can be used across functions to find the number of elements , because strlen The string length() function evaluates the length of a string , Yes  ' ' You can specify the end of a string .

原网站

版权声明
本文为[Nobaya]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202220511152963.html