About sizeof and strlen !!!

Source: Internet
Author: User

I encountered a small computation during the C ++ review. I still have a lot of knowledge. Let's start with your attention!

Char * str1 = "absde"; char str2 [] = "absde"; char str3 [8] = {'A' ,}; char ss [] = "0123456789 "; why sizeof (str1) = 4 sizeof (str2) = 6; sizeof (str3) = 8; sizeof (SS) = 11

First of all, the char type occupies one byte, so sizeof (char) is 1. To understand this, str1 is a pointer, but it only points to the string "absde. Therefore, sizeof (str1) is not the space occupied by strings, nor the space occupied by character arrays, but the space occupied by a character pointer. Therefore, sizeof (str1) = sizeof (char *) = 4. in C/C ++, a pointer occupies 4 bytes. str2 is a struct array. C/C ++ specifies that for an array, the total space occupied by this array is returned. Therefore, sizeof (str2) obtains the total space occupied by the string "absde. In "absde", there are
B s d e \ 0 six characters, so the str2 array length is 6, so sizeof (str2) = 6 * sizeof (char) = 6str3 has been defined as an array with a length of 8, so sizeof (str3) is similar to 8str4 and str2, '0' '1 '... '9' and '\ 0' are 11 characters in total, so SS occupies 8 space. For pointers, the sizeof operator returns the space occupied by the pointer, which is generally 4 bytes; for an array, sizeof returns the total space occupied by all elements in the array. Char * and char [] are easy to confuse and must be distinguished. In addition, char * = "AAA" is not recommended and should be avoided, while strlen does not distinguish array or pointer, returns the length until \ 0. In addition, strlen does not include \ 0 in the length of the string.



In general:

Sizeof is the length of the Data Type it refers,

Char * str1 = "absde ";

Str1 is a pointer, and the length of a char pointer is 4.

Char str2 [] = "absde ";

Char str3 [8] = {'A ',};

Char ss [] = "0123456789 ";

Str2, str3, and SS are all arrays. The result of sizeof is the length of the Data Type (array ).

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.