C the difference between sizeof and strlen

Source: Internet
Author: User

First, sizeof is an operator, strlen is a function, and the two are not on the same dimension.

The second sizeof is an operator that returns the length of an object or type name, without qualifying the type; strlen is a function in <string.h> that calculates the length of a C-style string (only C-style strings, which are not objects of the C + + String class).

Once again, just look at the C-style string

#include <stdio.h> #include <string.h> #define N 100int Main (void) {char a[] = "Abcdefhig";    Char b[n] = "Abcdefhig";    char *c = A;    printf ("A:sizeof%d strlen%d\n", sizeof (a), strlen (a));    printf ("B:sizeof%d strlen%d\n", sizeof (b), strlen (b)); printf ("C:sizeof%d strlen%d\n", sizeof (c), strlen (c));}

Output

a:sizeof strlen 9b:sizeof strlen 9c:sizeof 4 strlen 9

First line: For the first address of a C-style string, sizeof returns the length of the string as part of the string, and the strlen character is not counted.

The second line: sizeof returns the length of the object, the length of B is 100, and strlen only calculates the length of the ' n ' character.

Third line: For a pointer to the first address of the array, sizeof returns the object containing the size of the object, that is, the size of the pointer, 4 bytes, or strlen the length of B to the string, and does not include the end of '.

The difference between the two can be seen here.

Finally, sizeof is more useful as an operator and can calculate the length of a given object or type name, whether it is a built-in type or a custom class or struct. For a struct or class definition, the length of the struct or class returned by sizeof may not be the same as the "on paper" value because it involves an alignment policy in the computer's memory allocation, where the offset of the object's starting address is an integer multiple of 4.


C the difference between sizeof and 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.