The difference analysis of sizeof and strlen in C language _c language

Source: Internet
Author: User
Tags strlen

1, compile-time calculation operator sizeof, available types or variables to do parameters, calculate the size of memory consumption. If the type must be bracketed after sizeof, the variable name may not be bracketed. sizeof (x) can be used to define array dimensions such as:

Copy Code code as follows:

printf ("%d\n", sizeof (short));

The result of the output is the length of the short integer 2. When you use a struct type or variable as a parameter, the sizeof returns the actual size, and when used for the static array, sizeof returns the dimensions of all the arrays. The sizeof operator cannot return the dimensions of an array or an external array that is dynamically assigned.

2, Run-time calculation strlen, can only use char* to do parameters, and must be "" "end. The length of the string is computed. Such as:

Copy Code code as follows:

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

3, processing static array:

Copy Code code as follows:

Char str[20]= "0123456789";
int A=strlen (str); a=10; Strlen computes the length of the string, with the "end tag" for the string.
int b=sizeof (str); b=20; sizeof calculates the size of the allocated array str[20], which is not affected by the contents of the stored content.

4, processing pointers:

Copy Code code as follows:

char* ss = "0123456789";
sizeof (SS)//Result 4,

SS is a character pointer to a string constant, and sizeof gets the space occupied by a pointer. sizeof (*SS) result 1,*ss is the first character that gets the memory space of the first ' 0 ' of the string, which is a char type, and takes up 1 bytes. strlen (ss) = 10, to get the length of this string, be sure to use the strlen

The above is about sizeof and strlen the whole content of the difference, I hope you can enjoy

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.