#include <stdio.h>#include <string.h>int main (int argc, char **argv){ char *a = "0123456789"; char b[] = "0123456789"; char c[100] ="0123456789"; int d[100] ={0,1,2,3,4,5,6,7,8,9}; char e[8] = "abc0\0e123\0ed3\0f";
char f[] = "abc\\nt\012\xa1*2"; printf("char *a = \"%s\"\n",a); printf("char b[] = \"%s\"\n",b); printf("char c[100] = \"%s\"\n",c); printf("int d[100] = \"%s\"\n",d); printf("int e[8] = \"%s\"\n",e);
printf("int f[] = \"%s\"\n",f);
printf("--------------------\n"); printf("sizeof(a) = %d\n",sizeof(a)); printf("strlen(a) = %d\n",strlen(a)); printf("sizeof(b) = %d\n",sizeof(b)); printf("strlen(b) = %d\n",strlen(b)); printf("sizeof(c) = %d\n",sizeof(c)); printf("strlen(c) = %d\n",strlen(c)); printf("sizeof(d) = %d\n",sizeof(d)); printf("strlen(d) = %d\n",strlen(d)); printf("sizeof(e) = %d\n",sizeof(e)); printf("strlen(e) = %d\n",strlen(e));
printf("sizeof(f) = %d\n",sizeof(f));
printf("strlen(f) = %d\n",strlen(f));} /* ----- End of main() ----- */
Output:
[[Email protected] ~ /Coder] $ GCC 6-3.c 6-3.c: In the 'main' function: 6-3.c: 29: warning: the string used to initialize the character array is too long 6-3.c: 44: Warning: when the first parameter of 'strlen' is passed, it is converted between incompatible pointer types/usr/include/string. h: 399: Note: The 'const char * 'type is required, but the real parameter type is 'int *' [email protected] ~ /Coder] $. /. out char * A = "0123456789" char B [] = "0123456789" char C [100] = "0123456789" int d [100] = "" int e [8] =" abc0 "-------------------- sizeof () = 4 strlen (A) = 10 sizeof (B) = 11 strlen (B) = 10 sizeof (c) = 100 strlen (c) = 10 sizeof (d) = 400 strlen (d) = 0 sizeof (e) = 8 strlen (e) = 4
sizeof(f) = 11
strlen(f) = 10
The above examples can be summarized as follows:
Sizeof:
1. Operator.
2. It is used to calculate the pre-allocated size in the memory. Therefore, we can use sizeof to define the array dimension during pre-compilation.
3. sizeof (d) = 400 indicates that the array size is the product of each dimension * the size of the array element.
4. sizeof (e) = 8 we can see that the size of the array in the memory is based on the dimension, rather than subsequent initialization and assigned values.
Strlen:
1. It is a function. The header file is <string. h>
2. The strlen result can be calculated only during running. It is used to calculate the length of a string (it must end with "\ 0"), rather than the memory size occupied by the type.
3. strlen (e) = 4 indicates that strlen calculates the length of a string based on "\ 0.
The number of bytes occupied by the String constant "ABC \ nt \ 012 \ xA1 * 2" in the memory is
Abc -- 3
\ -- 1 Escape Character
NT -- 2
\ 012 -- 1 octal number
\ XA1 -- 1 hexadecimal number
* 2 -- 2
There is also a string Terminator. A total of 11 bytes.
Differences between sizeof and strlen