Difference between sizeof and strlen in C language, sizeofstrlen in C Language

Source: Internet
Author: User
Tags microsoft c

Difference between sizeof and strlen in C language, sizeofstrlen in C Language
Differences between sizeof and strlen in C Language
I. Essential differences
 
Sizeof is essentially different from strlen. Sizeof is a single-object operator in C language, such as ++ and --. It is not a function. sizeof has two levels of priority, and has a higher priority than Level 3 operators such as // and %. sizeof
The size of the storage space of the operand is given in bytes. Strlen is a function in C language.
. Strlen calculates the length of a string.
 
Ii. Usage differences
 
1. sizeof
 
The operands of sizeof can be data types, functions, and variables. The expressions are used as follows:
 
(1) Data Type
 
Sizeof (type)
 
For example, we can use sizeof (int) to calculate the storage space of an int type data ). Note that
When sizeof is a data type, parentheses are required. The value size is the storage space occupied by this data type.
The number of bytes.
 
(2) variables
 
Sizeof (variable name)
 
If int a is defined, you can use sizeof (a) to calculate the storage space occupied by the variable. Size
It depends on the type of.
 
Note: Because sizeof is an operator sizeof a or sizeof (. (Parentheses are not allowed ),
If the operand is an array name, the number of bytes occupied by the array. If the array name is used as a function parameter
The pointer is degraded during transmission.
 
(3) Expression
 
Sizeof (expression)
 
Sizeof can evaluate an expression. The Compiler determines the size based on the final result type of the expression,
Generally, expressions are not calculated. Example: sizeof (1 + 1.5)
 
(4) function call

 
Sizeof (function name ())
 
Sizeof can also be used to evaluate a function call. The result is the size of the function return type, and the function does not
Called. For example, the following function is defined:
 
Int myprint ()
{
Printf ("hello \ n ");
Return 0;
}
 
Int main ()
{
Printf ("% d", sizeof (mypaint ()));
Return 0;
}
Only the sizeof value of the type returned by the function is printed. If hello is not printed, the function myprint does not
Call.
 
The C99 standard stipulates that functions, expressions of undetermined types, and bit-field members cannot be
Calculate the sizeof value, that is, the following statements are incorrect:
For example, sizeof (myprint) (note that sizeof (myprint () is acceptable ))
Or sizeof a void return type function, such:
Void foo (){}
Sizeof (foo ());
And bit domain:
Struct S
{
Unsigned int f1: 1;
Unsigned int f2: 5;
Unsigned int f3: 12;
};
Sizeof (S. f1 );
 
2. strlen
 
Strlen is not widely used as sizeof. The strlen parameter must be a char * pointer.
The usage of strlen (int) is incorrect. Strlen computing must depend on Characters
The '\ 0' character in the sequence. strlen determines whether the Character Sequence ends by judging whether' \ 0' is encountered.
.
The calculation principle is similar to the following two statements.
While (* p! = '\ 0 ')
Length ++
 
Strlen usage: includes the following parameters:
 
(1) char * pointer

Strlen (pointer name)
 
If the parameter is a pointer, the length of the pointer pointing to the character sequence is calculated. (Use '\ 0' as the judgment flag) for example:
 
Define char * p = "hello world"; strlen (p) = 11, while sizeof (p) = 4. The 32-bit, 64-bit, and 8-bit are displayed in strlen.
Calculate the length of the string pointed to by the pointer, while sizeof calculates the memory occupied by the pointer.
.
 
(2) array
 
Strlen (array name)
 
If the parameter is an array, a pointer is actually passed, and strlen will process the pointer modulo according to the above
To process the array.
 
Let's look at the following example:

Char a [] = "hh ";
Strlen ();
 
Obviously, the result of strlen is 2. But what if the array is assigned a value like this?

Char a [] = {'h', 'H '};
Strlen ();
 
So what is the result of strlen (a) now? This number is not necessarily because strlen will go
Calculates the length of the string starting with address a. Since the previous value assignment method uses hh as a string
If you assign a value to the array, the string Terminator '\ 0' is assigned a value, and strlen checks that the ending character is stopped.
The second method is to assign a value without the terminator '\ 0' in the form of a single character.
The result obtained by sizeof is normal, and the end character cannot be found by strlen
Until the end is found. So this number is uncertain.


-------------------------


One example


 


# Define PATH_TMP "12345"


Static void test_sizeof_strlen (){


Char x msg = "12345 ";
Printf ("sizeof (msg) --- % d \ n", sizeof (msg ));
Printf ("strlen (msg) --- % d \ n", strlen (msg ));


Char array [] = "12345 ";
Printf ("sizeof (array) --- % d \ n", sizeof (array ));
Printf ("strlen (array) --- % d \ n", strlen (array ));


Printf ("sizeof (PATH_TMP) --- % d \ n", sizeof (PATH_TMP ));
Printf ("strlen (PATH_TMP) --- % d \ n", strlen (PATH_TMP ));


}


The output result:


Sizeof (msg) --- 4
Strlen (msg) --- 5
Sizeof (array) --- 6
Strlen (array) --- 5
Sizeof (PATH_TMP) --- 6
Strlen (PATH_TMP) --- 5


 


Bytes ------------------------------------------------------------------------------------------------------------------------


I. sizeof Concept
Sizeof is a type of single object operator in C language, such as other operators ++ and -- in C language.
It is not a function.
The sizeof operator provides the storage size of its operands in bytes.
The operand can be an expression or a type name enclosed in parentheses.
The storage size of the operands is determined by the type of the operands.
Ii. Usage of sizeof
1. Used for Data Types
Sizeof format: sizeof (type) data type must be enclosed in parentheses: sizeof (int)
2. Used for variables
Sizeof usage form: sizeof (var_name) or sizeof var_name variable names can be enclosed without parentheses. For example, sizeof (var_name) and sizeof var_name are all correct forms.
Brackets are more commonly used. Most programmers use this form.
Note: the sizeof operator cannot be used for function types, which are incomplete types or bit fields.
An incomplete data type refers to a data type with an unknown storage size,
For example, the array type of the unknown storage size, the structure or union type of the unknown content, and the void type. For example: sizeof (max) -- if the variable max is defined as int max ();
Sizeof (char_v) -- If char_v is defined as char char_v [MAX] at this time and MAX is unknown,
Sizeof (void)
The preceding statements are incorrect.
Iii. sizeof results (the following results are obtained in Linux v2.6 gcc v4)
The result type of the sizeof operator is size_t.
It is defined in the header file as: typedef unsigned int size_t;
This type ensures that it can accommodate the maximum object size.
1. ansi c officially specifies that the character type is 1 byte. Sizeof (char) = 1;
Sizeof (unsigned char) = 1;
Sizeof (signed char) = 1; 2. Other types are not specified in ansi c, and the size depends on the implementation.
Sizeof (int) = 4;
Sizeof (unsigned int) = 4;
Sizeof (short int) = 2;
Sizeof (unsigned short) = 2;
Sizeof (long int) = 4;
Sizeof (unsigned long) = 4;
Sizeof (float) = 4;
Sizeof (double) = 8;
Sizeof (long double) = 12;
3. When the operand is a pointer, sizeof depends on the compiler.
 
In Microsoft C/C ++ 7.0, the number of near class pointers is 2, and the number of far and huge class pointers is 4.
Generally, the number of pointer bytes in Unix/Linux is 4.
For example: char * p; // in Linux
Sizeof (p) = 4;
4. When the operand has an array type, the result is the total number of bytes of the array.
 
Example: char a [5];
Int B [5];
Sizeof (a) = 5;
Sizeof (B) = 20;
 
5. When the operand is a specific string or value, it is converted according to the specific type.
 
For example: sizeof (8) = 4; // auto convert to int type
Sizeof (8.8) = 8; // It is automatically converted to the double type. Note that it is not a float type.
Sizeof ("AB") = 3 // automatically convert to array type,
// The length is 4, not 3, because the last '\ n' character is added.
// Some documents indicate that the pointer type will be automatically converted (4 for Linux)
// It may be related to the operating system and compiler.
6. When the operands are of the Union type, sizeof is the maximum number of bytes of the member.
When the operand is a structure type, sizeof is the total number of bytes of its member type, including the supplementary bytes.
 
Let's talk about the example:
Union u {// for union
Char c;
Double d;
} U;
Sizeof (u) = max (sizeof (c), sizeof (d) = sizeof (1, 8) = 8;
Struct a {// For struct
Char B;
Double x;
} A; on Linux: sizeof (a) = 12;
Generally, sizeof (char) + sizeof (double) = 9; this is because when the compiler considers alignment, it inserts vacancies in the structure to control the address alignment of each member object.
If fully aligned, sizeof (a) = 16 because B is placed at the address with the offset of 0, which occupies 1 byte;
When storing x, the length of the double type is 8 and needs to be placed on the offset that can be divisible by 8. In this case, we need to add seven NULL bytes,
The offset is 8 at this time, and the length is 16 after x is put.
In this example, all the structure members should be placed in the 4-divisible address (the storage method of Linux). Here, we add 3 bytes, so it is 12.
7. When the operand is an array parameter or a function-type parameter in the function:
 
Sizeof indicates the pointer size. The value in Linux is 4.
Iv. Relationship between sizeof and other operators
The priority of sizeof is Level 2, which is higher than Level 3 operators such as/and %.
It can be combined with other operators to form an expression:
Example: int I = 10;
I * sizeof (int );
V. main use of sizeof
1. The main purpose is to communicate with routines such as storage allocation and I/O systems.
 
Example: void * malloc (size_t size); size_t fread (void * ptr, size_t size, size_t nmemb, FILE * stream );
2. Another major purpose is to calculate the number of elements in the array.
 
Example: void * memset (void * s, int c, sizeof (s ));
 


-----------------------------------------------


Differences between sizeof and strlen


Example 1: char ss [100] = "0123456789 ";


The result of Sizeof (ss) is 100. ss indicates the pre-allocated size in the memory, which is 100*1;


The Strlent (ss) returns 10. Its internal implementation is to calculate the length of the string in a loop until "\ 0.


Example 2: int ss [100] = "0123456789 ";


The result of Sizeof (ss) is 400. ss indicates the memory size, which is 100*4;


Strlen (ss) error. The strlen parameter can only be char * and must end with "\ 0.


Summary differences between sizeof and strlen


The result type of the inclusizeof operator is size_t, and typedef in the header file is of the unsigned int type. This type ensures that it can accommodate the maximum object size.


Inclusizeof is an operator and strlen is a function.


⒊ Sizeof can be a type parameter. strlen can only be a char * parameter and must end with "\ 0. Sizeof can also be used as a parameter using a function, such as: short f ();


Printf ("% d \ n", sizeof (f ()));


The output result is sizeof (short), that is, 2.


The sizeof parameter in the struct array is not degraded. If it is passed to strlen, It is degraded to a pointer.


Most compile programs calculate sizeof during compilation, which is the type or variable length. This is why sizeof (x) can be used to define the number of digits in an array.


Char str [20] = "0123456789 ";


Int a = strlen (satr); // a = 10;


Int B = sizeof (str); // B = 20;


The result of explain strlen can be calculated only when running. It is used to calculate the length of the string, rather than the memory size occupied by the type.


If it is a type after inclusizeof, brackets must be added. If it is a variable name, no brackets can be added. This is because sizeof is an operator rather than a function.


When a structure type or variable is used, sizeof returns the actual size. When a static space array is used, sizeof returns the size of all arrays. The Sizeof operator cannot return the size of the dynamically allocated array or external array.


When a struct array is passed as a parameter to a function, it is passed as a pointer rather than an array, and the first address of the array is passed. Passing an array in C ++ is always a pointer to the first element of the array. The Compiler does not know the size of the array, if you want to know the size of the array in the function, you need to use memcpy in the function to copy the array, and the length is limited by passing the other parameter.


To calculate the size of a structure variable, you must discuss the data issue.


The inclusizeof operator cannot be used for function types, which are incomplete types or bit fields. An incomplete data type refers to a data type with an unknown storage size, such as an array type with an unknown storage size, the structure or union type of the unknown content, and the void type.


 


Sizeof usage


First, we need to make it clear that sizeof is neither a function nor an unary operator. It is a special keyword similar to macro definition, sizeof (). The content in the brackets is not compiled during compilation, but is replaced by an alternative type, such as int a = 8; sizeof (). During the compilation process, no matter what the value of a is, the knowledge is replaced with the type sizeof (int) and the result is 4. What if sizeof (a = 6? It is also converted to the type, but note that because a = 6 is not compiled, the value of a is 8 after sizeof (a = 6) is executed, is unchanged.


① One of the main purposes of the sizeof operator is to communicate with routines such as storage allocation and I/O systems. For example:


Void * malloc (sizex_t size ),


Size_t fread (void * ptr, size_t size, size_t nmemb, FILE * stream)


② You can use it to look at the memory occupied by certain types of objects. For example:


Void * memset (void * s, int c, sizeof (s ))


③ When an object is dynamically allocated, the system can know the memory to be allocated.


④ It facilitates expansion of some types. In Windows, there are many structure types, and a special field is used to store the size of this type of bytes.


⑤ Because the number of bytes of the operand may change during implementation, we recommend that you use sizeof instead of constant calculation when the number of bytes involved in the operand is large.


⑥ If the operand is an array parameter in the function or a function-type parameter, sizeof gives the pointer size.


 


Conclusion:


① The meaning (positive/negative) of the highest bit of knowledge affected by unsigned will not change the data length, so:


Sizeof (unsigned int) = sizeof (int );


② The sizeof value of the custom type is equivalent to its type prototype. For example:


Typedef short WORD;


Sizeof (short) = sizeof (WORD );


③ When sizeof is used for a function, it will be replaced by the type of the function return value during compilation. For example:


Int f1 () {return 0 ;}


Cout <sizeof (f1 () <endl; // the return value of f1 () is int, so it is considered as int.


④ As long as it is a pointer, the size is 4. For example:


Cout <sizeof (string *) <endl; // 4


⑤ The size of the array is the product of each dimension × the size of the array element.

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.