Introduction and comparison of the use of sizeof () and strlen () functions in C language _c language

Source: Internet
Author: User
Tags arrays strlen

sizeof () function
1, what is it?
    sizeof is actually an operator, which is the same thing as those +,-, which is parsed when the program is compiled. Although we often see sizeof followed by parentheses, which are similar to functions, they are completely different from functions.
2, what's the use?
    sizeof is actually used to tell us the size, in bytes, of space that the compiler uses to open up space in storage for a particular data or data type.
3, how to use?
    sizeof (type), or sizeof (variable), can be obtained by the type or variable storage space. When used on a variable, you can also sizeof the variable without parentheses, but generally not (I'm usually just remembering a common usage ...). )。
4, what should you pay attention to when you use it?
(1) The amount of space that the sizeof returns is the size of the variable, not just the space it uses. It is similar to the concept of building area and saleable area of modern housing. So when it comes to structs, it's mostly about byte alignment. The
(2) cannot use a bit-domain member, such as a compiler, to determine what storage space is not. This should be better understood, because the sizeof return is in bytes of data, you let it go to the size of the bits, this is not deliberately difficult compiler. So the compiler uses the solution is unified not accept, even if you say you happen to be 8 bits, occupy a byte, compiler also ignore you. The data type returned by the
(3) sizeof is unsigned int. Because of the different types of data in C, the automatic conversion, sometimes do not pay attention to the problem may be, you can refer to the following program examples.
(4) Notice the difference between the array name and the pointer variable. Usually, we always think that the array name and the pointer variable are similar, but in the use of sizeof when the difference is very large, the logarithmic group name with sizeof return is the size of the entire array, and the pointer variable when the operation returned is the pointer variable itself occupies space, in 32-bit machine conditions are generally 4. And when the array name acts as a function argument, inside the function, the formal parameter is a pointer, so the size of the array is no longer returned.
5, instance Analysis
Source:

#include <stdio.h>
 
int main ()
{
    int ival = 3;
    printf ("The size of type int is%d \ n", sizeof (int));
    printf ("The size of Ival is%d\n", sizeof (ival));
    printf ("The size of Ival is%d\n", sizeof ival);
 
    if ((ival-sizeof (int)) < 0)
    {
        printf ("The return type is int\n");
    }
    else
    {
        printf ("The return type is unsigned int\n");
    }
 
    Char charraycon[7];
    char *CHP;
    CHP = Charraycon;
    printf ("The size of Charraycon is is%d, the size of CHP is%d\n", sizeof (Charraycon), sizeof (CHP));
 
    int iarraysize = 3;
    Char charrayvar[iarraysize];
    printf ("The size of Charrayvar is%d\n", sizeof (Charrayvar));
    return 0;
}

Run Result:

The size of type int is 4 the size an ival is 4 the size of a ival is 4 the return
type is
unsigned int
the The size of Charraycon is 7, the size of CHP is 4 the size of a
Charrayvar is 3

Results Analysis:
The first part of the code is basically a simple representation of usage.
The second part describes the third item of concern. Ordinarily, the value of Ival is 3, minus 4 should be-1, less than 0, and the output should be "he return type is int". But because when an int and a unsigned int work together, the default becomes unsigned int, so the result is a large number of unsigned int, which is greater than 0.
The third part of the code explains the difference between the array name and the pointer variable, and even if you point the pointer variable to the array name, the compiler can still tell the difference.

None of the above is considered under the C99 standard. Because there is a special case under the C99 standard, it is the use of indefinite arrays. When you use sizeof on an indefinite array name, the size of the entire array is returned, just like the fourth block of code in the instance. However, this is not performed at compile time, but is performed during the run phase of the program. Because at compile time, the compiler generally does not know the variable value is how much. (Of course in the example I directly assign a value of 3, may be inconvenient to understand, you can imagine Iarraysize is through scanf to get the actual value, and then declare the array). For this situation, the actual application is not much, we can treat as a special situation, or directly ignore the line ...
6 Summary
In fact, the role of sizeof is to tell us the size of the "building area" allocated to variables, as long as you remember this should be enough, whether this variable type is ordinary integer data, or structure, common body, enumeration ... With that in mind, when we go back to wondering what the value of sizeof is returning for different data type operations, it's just a matter of figuring out how much "building area" that data type is going to consume.

Strlen () function
the C library function size_t strlen (const char *STR) calculates the length of the string str, but does not include terminating null characters.

Statement
The following is the declared strlen () function.

size_t strlen (const char *STR)

Parameters
STR-This is the length of the string to compute.

return value
This function returns the length of the string.

Example
The following example shows the use of the strlen () function.

#include <stdio.h>
#include <string.h>

int main ()
{
  char str[50];
  int Len;

  strcpy (str, "This is yiibai.com");

  len = strlen (str);
  printf ("Length of |%s| is |%d|
", str, len);
  
  return (0);
}

Let's compile and run the above program, which will produce the following results:

Length of | This is yiibai.com| Is |26|


the usage difference between sizeof and strlen
1. The result type of the sizeof operator is size_t, which is typedef in the header file as the unsigned int type. This type guarantees the byte size of the maximum object that the implementation is built to hold.

2. sizeof is the operator (c + + keyword) and strlen is a function.

3. SizeOf can be used to make parameters, strlen can only use char* to do parameters, and must be "" "End of". sizeof can also use functions to do parameters, such as:

Short f ();
printf ("%d\n", sizeof (f ()));

The result of the output is the size of the type of the return value, that is, sizeof (short) = 2.

4. The parameters of the array do sizeof are not degraded, passing to the strlen is degraded to the pointer. Most compilers compute the sizeof at compile time, the type or the length of the variable, which is why sizeof (x) can be used to define the array dimension.

Char str[20]= "0123456789";
int A=strlen (str); a=10;
int b=sizeof (str); b=20;

The results of the strlen are computed at run time, and are used to compute the length of the string, not the type that is the size of the memory.

5. After sizeof if the type must be bracket, if the variable name can be without brackets. This is because sizeof is an operator and not a function.

6. When applied to a struct type or variable, sizeof returns the actual size, and when applied to a static space array, the sizeof gets the dimensions of all the arrays. The sizeof operator cannot return the dimensions of an array or an external array that is dynamically assigned.

7. The array is passed as a parameter to the function newsletters is a pointer rather than an array, passing the first address of the array, such as:

Fun (char [8])
fun (char [])

are equivalent to Fun (char *).

In C + + The parameter passing array is always passed a pointer to the first element of the array, and the compiler does not know the size of the array. If you want to know the size of an array within a function, you need to do this:

After entering the function, it is copied with memcpy, and the length is transmitted by another parameter.

Fun (unsiged char *p1, int len)
{
 unsigned char* buf = new unsigned char[len+1]
  memcpy (buf, p1, Len);
}

sizeof to the pointer, the result is the corresponding type:

char* ss = "0123456789";
sizeof (SS)

The result is 4 => SS is a character pointer to a string constant, sizeof gets the space occupied by a pointer, it should be a long integer, so it is 4. sizeof (*SS) result 1, => *ss is the first character, in fact, is to obtain the string of the first "0" occupied by the memory space, is a char type, accounting for 1 bytes, strlen (ss) = >>>> If you want to get the length of this string, you must use Strlen.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.