Comparison between strlen and sizeof

Source: Internet
Author: User
Tags first string

1. strlen () is used to calculate the length of the specified string S, excluding the ending character '\ 0 '. Strlen only works as a counter. It starts scanning from a memory location (which can start with a string, a location in the middle, or even an uncertain memory area, Until the first string Terminator '\ 0' is met, Then return the counter value, inProgramRuntime computing.

Original article:

http://baike.baidu.com/view/736226.htm

2. sizeof is an operator that can be used for any variable name, type name, or constant value. It does not need parentheses when used for variable names (not array names) or constants.

It works during compilation rather than runtime.

Sizeof () is returned after the variable Declaration Actual memory bytes occupied , Not the length. In addition, sizeof is not a function, but an operator. strlen is a function.

3. example

char CHS [] = {'A ', 'C', '/0', 'z', '3', 'D'}; // sizeof (CHS) = 6; and strlen (CHS) = 2.

http://www.cnblogs.com/ffhajbq/archive/2012/11/14/2769211.html

char STR [20] =" 0123456789 ";

int A = strlen (STR ); // A = 10;

int B = sizeof (STR ); // B = 20;

4. sizeof can be used as a parameter, strlen can only use char * as a parameter, and must end with ''\ 0. If sizeof is a type, you must add an arc. If it is a variable name, you can do not add an arc. This is because sizeof is an operator and not a function. The sizeof operator cannot return the size of the dynamically assigned array or external array.

the sizeof parameters of arrays are not degraded, passing to strlen degrades to a pointer (because strlen is a function ).

5. when sizeof is used, a special case is that the array name changes to pointer,

char array [3] = {'0 '};

sizeof (array) = 3;

char * P = array;

strlen (p) = 1; // The sizeof (p) result is 4

when passing an array name to a function, it will be completely degraded into a pointer.

Original article:

Http://baike.baidu.com/view/1356720.htm

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.