sizeof, strlen, string, array, all the whole piece, you know?

Source: Internet
Author: User

Write in front

sizeof, strlen, strings, arrays, mentioned these concepts, I believe that people who have learned C language can be familiar with, but also can talk well, but, in the actual application, when these content intertwined, we do not necessarily can make clear, the purpose of this article is to help you to summarize the relevant knowledge.

Body

Look at a piece of code first

1#include <stdio.h>2#include <stdlib.h>3 4 voidTestchar (Charstr[])5 {6printf"%d%d\n",sizeof(str), strlen (str));7 }8 9 voidTestint (intarr[])Ten { Oneprintf"%d\n",sizeof(arr)); A } -  - intMain () the { -     CharStr[] ="ABC"; -printf"%d%d\n",sizeof(str), strlen (str));//4 3 -  +     Charstr1[Ten] ="ABC"; -printf"%d%d\n",sizeof(STR1), strlen (STR1));//Ten 3 +  A     CharDog[] ="Wangwang\0miao"; atprintf"%d%d\n",sizeof(dog), strlen (dog));//8 -Testchar (dog);//4 8 -  -     Char*cat ="Wangwang\0miaomiao"; -printf"%d%d\n",sizeof(cat), strlen (cat));//4 8 -      in     intarr[Ten] = {0 }; -printf"%d%d\n",sizeof(arr),sizeof(arr[ One]));//4 toTestint (arr);//4 +  -     return 0; the}

Results

Before explaining the above example, let's start by talking about sizeof and strlen.

Grammatical differences in nature:

sizeof is an operator and strlen is a function.

The scope of application is different:

For sizeof (name), name can be either a variable name or a type name, and for strlen, the argument must be of type char*, that is, strlen is used only for strings.

The most serious--from the bottom to the essence

strlen (PTR) is executed from the memory pointed to by the parameter PTR, counting down until the contents in memory are all 0 (that is, ' \ s ') (no count is made on ' \ S '). using strlen to measure the length of a string is actually based on this principle.

the execution mechanism of sizeof is: If name is a type name, the size of the type is obtained (the size of the so-called type, that is, if there is a variable of that type, the number of bytes that the variable occupies in memory), if name is a variable name ,sizeof (name) does not actually access the variable , but first learns the type of the variable and then returns the size of the type (that is, a complex type such as a struct, which, at compile time, also records its size according to its various fields, so It is not difficult to get type size by type. In other words, the operand of sizeof is essentially a type . If name is a variable name, then how sizeof "treats" the type of name will be a key issue. (We will have a deep understanding of this point later)

The above-mentioned point, is to understand the good sizeof and strlen only way, is a universal standard. Below, we will analyze the above example with this criterion.

A.

Char " ABC ";p rintf ("%d%d\n"sizeof(str), strlen (str)); 4 3

Here, the string is declared in the form of an array, and the compiler automatically appends the string with ' s ', so the number of elements in the array is 4 instead of 3. for sizeof (str), sizeof treats str as char [4]l type variable, so the result of sizeof (STR) is the amount of space the entire array occupies. For strlen (str), it starts counting from the memory that the STR points to, until it encounters a total of 0 of memory ('% '), so the result is finally 3.

B.

Char str1["ABC";p rintf ("%d%d\n"  sizeof//3

The compiler assigns a space of 10 array element sizes to char str1[10], which is not related to the string that initializes it, so sizeof (STR1) gets 10.

C.

Char " Wangwang\0miao " ;p rintf ("%d%d\n"sizeof//8//  4 8

The first two sentences are the same as in a, and sizeof (dog) outputs the memory size of the entire array (including the compiler plus the ' strlen '), and the dog encounters ' \ ' stops, so the output is 8.

Look back at the function call, the array name of the dog as a function argument passed in, we will review the Testchar function

void Testchar (char  str[]) {    printf ("%d%d\n"sizeof  (str), strlen (str));}

We found that sizeof (STR) did not get 14 as much as sizeof (dog), but got 4. This is because STR is a function parameter, and although it appears in the form of an array name, the argument passed to it is indeed an array name, but sizeof treats it as a pointer to a char* type, so the result of sizeof (STR) is 4 of the space occupied by the char * type. As for strlen (str), as we said earlier, the mechanism it performs is to count down from the memory pointed to by STR, until it encounters a '/', so it still gets 8.

D.

Char " Wangwang\0miaomiao " ;p rintf ("%d%d\n"sizeof//4 8

Since cat is explicitly declared as char*, sizeof treats it as a pointer and gets 4.

D.

int arr[0  };p rintf ("%d%d\n"sizeof  sizeof(arr[//4//4

As I said earlier, when the array name appears as a function parameter, sizeof just treats it as a pointer, otherwise, sizeof thinks it represents the entire array , so sizeof (arr) gets the entire array of bytes 40, while Testint (arr) The result is a pointer of type int* of length 4.

sizeof (INT[11]), it is clear that the array is out of bounds, but there is no run-time error. The reason is that, according to the judging criteria we give, sizeof does not actually visit arr[11], and as the Arr declares, sizeof knows that arr[11] is an int, so it returns the size of the int type.

As for Testint (arr), the truth is the same as the Testchar (dog) in B.

Finally, based on the above discussion, the coding criteria are given:

1. Never use sizeof to find the string length! It's not a job, so you'll never get the right answer.

2. Don't be smart about using the code such as sizeof (ARR)/sizeof (arr[0]) to find the length of the array! Nor does sizeof do the job. If arr is a function parameter, the resulting result will be wrong (unless you just declare int arr[1] or char arr[4] in a 32-bit system, but this is purely coincidental). Since it is an array, the length is naturally known, and the length of the array itself, is the folly of one single swoop.

Write it in the back.

The purpose of this paper is to make readers have an essential understanding of the basic knowledge--sizeof and strlen of C language, and have a correct and clear judgment on the related error-prone and easy-to-mix problems. Because in the next Caishuxueqian, the error is unavoidable, hope that the vast number of readers to actively criticize, your criticism is precisely in the next step forward inexhaustible momentum.

sizeof, strlen, string, array, all the whole piece, you know?

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.