The difference between sizeof and strlen in C language
I. Essential differences
sizeof and strlen have an essential difference. sizeof is the C language of a single-eye operator, such as + + 、--, and so on, is not a function, sizeof priority is 2, the ratio/,% and other 3-level operators are high priority, sizeof
The size of the storage space for the operand as a byte. And Strlen is a function that is made by C language
Provided by the standard library. Strlen calculates the length of a string.
Two. Usage differences
1.sizeof
The operands of sizeof can be data types, functions, variables, and expressions are used in the following ways:
(1) Data type
sizeof (type)
For example, we want to calculate the storage space for an int data can be used: sizeof (int). It is important to note that
The operand of sizeof is the data type when the parentheses are added. The value is the size of the storage space for the data type
The number of bytes between.
(2) Variables
sizeof (variable name)
If you define int A, you can use sizeof (a) to calculate the storage space occupied by a variable. Specific size
is related to the type of a.
Note: Because sizeof is an operator, sizeof a or sizeof (a) can. (You can not use parentheses),
If the operand is an array name, the number of bytes of memory that are consumed by the group. If the array name does the argument to the function
Degenerate to a pointer when passed.
(3) expression
sizeof (expression)
sizeof evaluates an expression, and the compiler determines the size based on the end-result type of the expression.
Expressions are generally not evaluated. For example: sizeof (1+1.5)
(4) Function call
sizeof (function name ())
sizeof can also evaluate a function call, the result of which is the size of the function return type, and the function does not
is called, for example, to define the following function:
int Myprint ()
{
printf ("hello\n");
return 0;
}
int main ()
{
printf ("%d", sizeof (Mypaint ()));
return 0;
}
The result is that only the sizeof value of the function return type is printed, and the Hello description function is not printed myprint does not
Call.
The C99 standard stipulates that functions, expressions that cannot determine types, and bit-field (Bit-field) members cannot be
Calculates the sizeof value, that is, the following notation is wrong:
such as: sizeof (Myprint) (Note that sizeof (Myprint () is possible))
or sizeof a function of void return type such as:
void foo () {}
sizeof (foo ());
and bit fields:
struct S
{
unsigned int f1:1;
unsigned int f2:5;
unsigned int f3:12;
};
sizeof (S.F1);
2.strlen
Strlen's application is not as extensive as sizeof, Strlen's argument must be a pointer to char *, if
Strlen calculation data type strlen (int) This usage is wrong. The strlen calculation must depend on the character
The ' strlen ' character in the sequence determines whether the sequence of characters ends by judging whether or not it encounters '
Of
It calculates the principle similar to the following two statements
while (*p! = ' + ')
length++
Strlen usage: Divided into the following types of parameters
(1) char * pointer
strlen (pointer name)
If the argument is a pointer, it calculates the length of the character sequence that the pointer points to. (with ' + ' as the judging sign) for example:
Define char *p= "Hello World"; strlen (p) = 11, and sizeof (p) = 4. 32-bit under 4, 64-bit under 8, you can see strlen
Computes the length of the string pointed to by the pointer, and sizeof calculates that the memory used by the pointer itself is empty
The size of the room.
(2) array
strlen (array name)
If the argument is an array, the actual pass is a pointer, and the strlen will follow the module that handles the pointer above
Handle the array as you type.
We can look at the following example:
Char a[]= "HH";
Strlen (a);
It is clear that the result of strlen is 2. But what if the array is assigned such a value?
Char a[]={' h ', ' H '};
Strlen (a);
So what is the result of strlen (a) now? This number is not necessarily the reason why strlen will go
Calculates the length of the string at which a address begins, since the previous assignment would have HH in the form of a string
Assigning a value to an array assigns a value to the string Terminator ' \ Strlen ', at which point the end character is checked to stop
Calculation, and the second method of complex values is to assign a value with a single character without a Terminator ' \ s ', when we use
sizeof gets the result is normal, and with strlen because cannot find the Terminator, will continue the calculation until
Until the Terminator is found. So this number is not sure.
-------------------------
One example
#define PATH_TMP "12345"
static void Test_sizeof_strlen () {
Char *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
--------------------------------------------------------------------------------------------------------------- ---------
First, the concept of sizeof
sizeof is a single-eye operator of C, such as the other C language operators + + 、--.
It is not a function.
The sizeof operator gives 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 operand is determined by the type of the operand.
Second, the use of sizeof method
1. For data type
sizeof usage form: sizeof (type) data type must be enclosed in parentheses: sizeof (int)
2. For variables
sizeof use form: sizeof (var_name) or sizeof var_name variable names can be enclosed without parentheses. such as sizeof (Var_name), sizeof var_name, etc. are all in the right form
The use of parentheses is more common, and most programmers take this form.
Note: The sizeof operator cannot be used for function types, incomplete types, or bit fields.
An incomplete type refers to a data type with an unknown storage size.
such as unknown storage size array type, unknown content structure or union type, void type, and so on. For example: sizeof (max)--When the variable max is defined as int max ();
sizeof (CHAR_V)--when CHAR_V is defined as Char Char_v[max] and MAX is unknown,
sizeof (void)
These are not the correct forms.
Third, the results of sizeof (the following results are obtained in the 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 guarantees that the byte size of the largest object being built can be accommodated.
1, ANSI C formally stipulates that the character type is 1 bytes. sizeof (char) = 1;
sizeof (unsigned char) = 1;
sizeof (signed char) = 1; 2. Other types are not specified in ANSI C, and size depends on 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. sizeof relies on the compiler when the operand is a pointer.
In Microsoft c/c++7.0, the near class pointer byte count is 2,FAR, huge class pointer byte number is 4.
The number of pointer bytes for general 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 in 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, the corresponding conversion according to the specific type.
For example: sizeof (8) = 4; automatic conversion to int type
sizeof (8.8) = 8; Automatic conversion to double type, note, not float type
sizeof ("ab") = 3//auto-Convert to array type,
The length is 4, not 3, because the last ' \ n ' symbol is added
There is data that will automatically convert to pointer type (Linux is 4)
May have a relationship with the operating system and the compiler
6. When the operand is a union type, sizeof is the number of bytes of its largest byte member.
When the operand is a struct type, sizeof is the total number of bytes of its member type, including the supplemental bytes.
Let's take an example to say:
Union u{//For Union
char c;
Double D;
}u;
sizeof (U) = max (sizeof (c), sizeof (d)) = sizeof (1,8) = 8;
struct a{//for structs
Char b;
Double X;
}a; On Linux: sizeof (a) = 12;
and generally sizeof (char) + sizeof (double) = 9; This is because the compiler, when considering alignment issues, inserts a vacancy in the structure to control the address alignment of each member object.
But if fully aligned, sizeof (a) = 16, because B is placed at an offset of 0, accounting for 1 bytes;
When storing x, the double type has a length of 8 and needs to be placed on an offset that is divisible by 8, which requires 7 empty bytes.
Reaches 8, when the offset is 8, and the length after X is 16.
In this example, all struct members are placed in an address that is divisible by 4 (the way Linux is stored), where it is 3 bytes, so it is 12.
7, when the operand is an array parameter in a function or a formal parameter of a function type:
sizeof gives the size of its pointer, with a value of 4 in Linux.
Iv. the relationship between sizeof and other operators
sizeof has a priority level of 2, and a 3-level operator with a higher precedence than/,%, and so on.
It can form an expression together with other operators:
For example: int i = 10;
I * sizeof (int);
V. Main uses of sizeof
1. The main purpose is to communicate with routines such as storage allocation and I/O systems.
For example: void *malloc (size_t size); size_t fread (void *ptr, size_t size, size_t nmemb, FILE * stream);
2, the other main purpose is to calculate the number of elements in the array.
For example: void *memset (void *s, int c, sizeof (s));
-----------------------------------------------
The difference between sizeof and strlen
Example 1:char ss[100]= "0123456789";
Sizeof (ss) results for 100,SS indicate the size of the pre-allocated in memory, 100*1;
The strlent (ss) result is 10, and its internal implementation is to use a loop to calculate the length of the string until "s" is reached.
Example 2:int ss[100]= "0123456789";
Sizeof (ss) results for 400,SS representing the size in memory, 100*4;
Strlen (ss) error, the Strlen parameter can only be char* and must end with "\".
Summarize the differences between sizeof and strlen
The result type of the ⒈sizeof operator is size_t, and its typedef in the header file is of type unsigned int. This type guarantees that the byte size of the largest object being built can be accommodated.
⒉sizeof is an operator, and strlen is a function.
⒊sizeof can use the type parameter, strlen can only use char* to do parameters, and must be "" "to end. sizeof can also use functions to do parameters, such as: short f ();
printf ("%d\n", sizeof (f ()));
The result of the output is sizeof (short), which is 2.
⒋ array does sizeof parameter does not degenerate, passes to the strlen to degenerate as the pointer.
⒌ most compilers have calculated sizeof at compile time, which is the length of the type or variable. This is why sizeof (x) can be used to define the number of array bits.
Char str[20]= "0123456789";
int A=strlen (SATR); a=10;
int b=sizeof (str); b=20;
The results of the ⒍strlen are calculated at run time and are used to calculate the length of the string, not the size of the type in memory.
⒎sizeof after if the type must be parentheses, if the variable name can be no parentheses. This is because sizeof is an operator and not a function.
⒏ when a struct type or variable is used, sizeof returns the actual size. When a static array of spaces is used, sizeof returns the dimensions of all arrays. The sizeof operator cannot return the dimensions of an array that is dynamically allocated or an outer array.
The ⒐ array is passed as an argument to a function as a pointer rather than an array, passing the first address of the array. Passing an array in C + + is always a pointer to the first element of the array, and the compiler does not know the size of the array, and if you want to know the size of the array within the function, you need to copy the array with memcpy in the function, and the length is passed by another parameter.
⒑ to calculate the size of the structure variable, it is necessary to discuss the problem of data.
The ⒒sizeof operator cannot be used for a function type, an incomplete type, or a bit field. An incomplete type is a data type with unknown storage size data, such as an array type with unknown storage size, structure or union type of unknown content, void type, and so on.
Application of sizeof
The first thing to make clear is that sizeof is not a function or unary operator, it is a special keyword like a macro definition, sizeof (). The contents of parentheses are not compiled during compilation, but instead are substituted types, such as int a=8; sizeof (a). During compilation, knowledge is replaced with type sizeof (int) regardless of the value of a, and the result is 4. What if sizeof (a=6)? It is also the same as the type of a, but note that since a=6 is not compiled, after executing sizeof (A=6), the value of a is still 8, which is constant.
One of the main uses 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)
② uses it to look at the cells that some type of object occupies in memory. For example:
void * memset (void * s, int c, sizeof (s))
③ when assigning an object dynamically, you can let the system know how much memory to allocate.
④ facilitates some types of expansion. There are many struct types in windows that have a dedicated field to hold the byte size of the type.
⑤ because the number of bytes of the operand may change when implemented, it is recommended that sizeof be used instead of the constant calculation when the operand byte size is involved.
⑥ if the operand is an array parameter in a function or a formal parameter of a function type, sizeof gives the size of its pointer.
Conclusion:
①unsigned impact knowledge The meaning of the highest bit (positive/negative), the data length is not changed, so:
sizeof (unsigned int) = = sizeof (int);
The sizeof value of the ② custom type is equivalent to its type prototype. Such as:
typedef short WORD;
sizeof (short) = = sizeof (WORD);
③ uses sizeof for the function, which is replaced by the type of the function return value during the compilation phase. Such as:
int F1 () {return 0;}
Cout<<sizeof (F1 ()) <<endl; The F1 () return value is int and is therefore considered int.
④ as long as the pointer, the size is 4. Such as:
Cout<<sizeof (string*) <<endl; 4
The size of the ⑤ array is the product of the number of dimensions x the size of the array element.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
The difference between sizeof and strlen in C language