sizeof strlen detailed difference comparison

The difference between sizeof and strlen:

1. The result type of the sizeof operator is size_t, which is typedef in the header file as an unsigned int type.

This type is guaranteed to hold the byte size of the largest object created by the realization.

2. sizeof is an operator, strlen is a function.

3. sizeof can use type as a parameter, strlen can only use char* as a parameter, and it must end with "\0".

sizeof can also use functions as parameters, such as:

short f();

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

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

4. The sizeof parameter of the array does not degenerate, and it degenerates to a pointer when passed to strlen.

5. Most compilers calculate sizeof when compiling. It is the length of the type or variable. This is why sizeof(x) can be used to define the dimension of the array.

charstr[20]=“0123456789”;

int a=strlen(str);//a=10;

int b=sizeof(str);//and b=20;

6. The result of strlen can be calculated at runtime, and is used to calculate the length of the string, not the size of the memory occupied by the type.

7. After sizeof, brackets must be added if it is a type, and brackets are not required if it is a variable name. This is because sizeof is an operator and not a function.

8. When applied to a structure type or variable, sizeof returns the actual size,

When using a statically spaced array, sizeof returns the size of the entire array.

The sizeof operator cannot return the size of dynamically allocated arrays or external arrays

9. When the array is passed as a parameter to the function, the pointer is passed instead of the array, and the first address of the array is passed

Guess you like

Origin blog.csdn.net/qq_45849625/article/details/113483683