The C language is not simple: sizeof, And the C language sizeof

Source: Internet
Author: User

The C language is not simple: sizeof, And the C language sizeof

Q: How many keywords are in C language?

Answer: 32.

It doesn't matter if you cannot answer the question. Normally, we are playing the art of the program, rather than carrying numbers. However, this special number 1 <5 is also very memorable -.-.


Q: Is sizeof a function or a keyword?

When you see this problem for the first time, you may find it a bit confusing. sizeof is a function, because sizeof is followed by parentheses. This is obviously a symbol of a function. But now that I have asked this question, you may have guessed that sizeof is not a function and it is a keyword! For a long time, because of sizeof's "standard usage", sizeof is easily understood as a function. Run the following code:

#include <stdio.h>int main(){    int num = 5;    printf("%d\n", sizeof(num));    printf("%d\n", sizeof(int));    printf("%d\n", sizeof num);    getchar();    return 0;}
Sizeof num can output 4 correctly. It can be seen that it is really not a function. However, sizeof int is incorrect. It produces the following error:

error: expected primary-expression before "int"
Because int can only be followed by auto, unsigned, etc. Besides, how can we understand sizeof int? I want to calculate the size? I still want to represent the int variable of the "sizeof" type.

The following is a summary after reading the relevant information:

When you want to calculate the size of a variable, such as a variable of the basic type (int, double) and a struct variable (instance), no parentheses are required,

Brackets cannot be omitted when a type is to be calculated.

In any case, a bracket is added. The first is unity, which makes the program more readable and error-prone. My goal is not to omit this bracket, but to omit it will not make things better. What I want to express is sizeof, on the other hand: because we now know that sizeof is not a function but a keyword, its nature is completely different. The function is determined at runtime, while the keywords are determined at compilation. Try to run the following program:

#include <stdio.h>int main(){    int cc[10];    printf("%d\n", sizeof cc[999999999]);    getchar();    return 0;}

The above program does not go wrong, but outputs 4 correctly. This is not because sizeof really finds the memory that is offset by 999999999 locations relative to the first cc address. As described above, sizeof is determined during compilation, therefore, it determines the size based on the cc [X] type. Because sizeof does not access these addresses, there is no problem in the above program syntax, but logically it seems that there is no practical significance. Can you think of something that proves that sizeof really didn't "execute" in brackets? It is actually quite simple. Try to run the following code:

printf("%d\n", sizeof(printf("hactrox")));
The result is 4, and "hactrox is not output! If sizeof is not output, it means that sizeof does not call anything in brackets, but why is it 4? Because sizeof is determined by type. For printf or function, sizeof is determined by its return value type. Because printf returns the number of output characters, which is of the int type, it is equivalent to sizeof (int), so it is 4. You may not know this feature of printf. Try to run the following code:

#include <stdio.h>int main(){int num = printf("hactrox\n");    printf("%d\n", num);    getchar();    return 0;}
A more direct example is as follows:

# Include <stdio. h> int fun () {printf ("hactrox"); return 5;} int main () {printf ("% d \ n", sizeof (fun ())); // The function is not executed, and 4 getchar (); return 0;} is output based on the return value type ;}

There is another thing to note about sizeof. Try running the following program in your mind and get a result before running it:

#include <stdio.h>#define SIZE_OF_ARRAY (sizeof(array) / sizeof(array[0]))int main(){    int array[] = {1, 2, 3, 4, 5};    for(int d = -1; d < (SIZE_OF_ARRAY-1); d++)        printf("%d\n", array[d+1]);        printf("END\n");    getchar();    return 0;}
Is it different from what you think? Why is no output for an array? The reason is that sizeof returns an unsigned int. When int is compared with an unsigned int, int is converted to an unsigned int. When int is <0, this forced conversion is naturally tragic, the result is MaxValue (unsigned int)-abs (int). When d =-1, it is naturally converted into a very large number, of course, the for Loop will not be executed.

# Include <stdio. h> int main () {int a =-1; unsigned int B = 10000; if (a> B) printf ("a> B \ n "); else printf ("a <B \ n"); a = (unsigned int) a; printf ("% u \ n", ); // unsigned int should be output by % u instead of % d getchar (); return 0 ;}

Finally, what should I do if I want to output the maximum value of the unsigned int in C language? TIPS:

# Include <stdio. h> int main () {printf ("Max value of unsigned int is: % u \ n ",~ (Unsigned int) 0); // The result can only be expressed as printf ("Max value of int is: % d \ n ",~ (Unsigned int) 0> 1); // % d is used for the result, and % u can be used to indicate getchar (); return 0 ;}



What is the difference between sizeof and strlen in C language?

The strlen (char *) function is used to calculate the actual length of the string. The method is from the beginning to the First '\ 0'. If you only define that the initial value is not assigned to it, the result is not correct. It will be searched from the first address of aa until '\ 0' is stopped.
Char aa [10]; cout <strlen (aa) <endl; // The result is uncertain.
Char aa [10] = {'\ 0'}; cout <strlen (aa) <endl; // The result is 0.
Char aa [10] = "jun"; cout <strlen (aa) <endl; // The result is 3.
The sizeof () function returns the amount of memory occupied after variable declaration, not the actual length.
Sizeof (aa) returns 10
Int a [10]; sizeof (a) returns 40
1. The result type of the sizeof operator is size_t. In the header file, typedef is of the unsigned int type.
This type ensures that it can accommodate the maximum object size.
2. sizeof is an operator and strlen is a function.
3. 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, for example:
Short f ();
Printf ("% d \ n", sizeof (f ()));
The output result is sizeof (short), that is, 2.
4. the sizeof parameter of the array is not degraded. If it is passed to strlen, It is degraded to a pointer.
5. Most compilation programs calculate sizeof as a type or variable length during compilation. This is why sizeof (x) can be used to define the array dimension.
Char str [20] = "0123456789 ";
Int a = strlen (str); // a = 10;
Int B = sizeof (str); // B = 20;
6. The strlen result can be calculated only during running. It is used to calculate the string length, not the memory size occupied by the type.
7. If sizeof is a type, you must add an arc. If it is a variable name, you can do not add an arc. This is because sizeof is an operator and not a function.
8. When applicable to a structure type or variable, sizeof returns the actual size. When applicable to static space arrays, sizeof returns the size of all arrays.
The sizeof operator cannot return the size of the dynamically assigned array or external array.
9. When an array is passed as a parameter to a function, the pointer instead of an array is passed, and the first address of the array is passed,
For example:
Fun (char [8])
Fun (char [])
It is equivalent to fun (char *)
In C ++, passing an array by parameters 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 do this:
After entering the function, copy it with memcpy. The length is passed in by another parameter.
Fun (unsiged char * p1, int len)
{
Unsigned char * buf = new unsigned char [len + 1]
Memcpy (buf, p1, len );
}
We usually use sizeof and strlen to calculate the length of the string array.
I have read the full text of ......>

What is the role of the sizeof operator in C language?

It is usually used to calculate the size of a variable or type, in bytes.
For example, sizeof (char) = 1, sizeof (int *) = 4 are the size of the computing type, char is a byte, int * is 4 bytes (in fact, the pointer in 32-bit system is 4 bytes, such as char * and void)
For example, char a; then sizeof (a) = 1
Int B; then sizeof (B) = 4 (this is related to the compiler, and some are 2)

In addition, when calculating the structure and class size, you can also use sizeof to calculate the bytes occupied by the class or structure. the calculation method varies depending on the compiler, but the basic algorithms are the same. For example, char is 1 byte, int * is 4 bytes, and double is 8 bytes, double * is 4 bytes. some compilers perform alignment and some do not. however, this generally does not make much sense.

In terms of applications, such
1. Calculate the number of array elements
Int a [] = {1, 2, 4, 5, 6, 7, 8, 9, 20 };
Sizeof (a)/sizeof (a [0]) is the size of array a divided by the size of a single element. The result is the number of elements of array a, which is more convenient than the number of itself, especially when the number is large. when traversing an array, for example, for (int I = 0; I <sizeof (a)/sizeof (a [0]); ++ I ){...}
In this way, errors are not easy. Otherwise, one or more errors may occur.

2. dynamically apply for memory (when malloc, calloc, and realloc are used)
For example, to apply for a memory segment to store 30 double Data Types
You can use (double *) malloc (sizeof (double) * 30) to apply for 8*30 bytes of space and return the first address to a double * type variable.

3. When some function parameters require the number of bytes

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.