Sometimes easy to use sometimes pit daddy's sizeof

Source: Internet
Author: User

The operator in C is sizeof (type_name) and can be used with any variable name, type name, or constant value, and it does not need parentheses when used for variable names (not array names) or constants. Note that sizeof is an operator, and it works at compile time, not at runtime. The return value is the unsigned int class.

You can see from the name that size is the length of the measurement type, but there is a problem here: when passing in a normal type, it is certainly the length of the class, and the structure is OK. But the problem with passing in the array is that the array name is a pointer, so what is the measured length of the incoming array, or the length of the memory that the pointer is pointing to? I'm going to get a hole here!

And look at the following code:

#include <stdio.h>voidMain () {voidPrintint*c,intd[][3]); inta[Ten],b[2][3]; printf ("%d\t%d\t",sizeof(a),sizeof(b)); Print (A, b);}voidPrintint*c,intd[][3]) {printf ("%d\t%d\n",sizeof(c),sizeof(d));}

The results could be unexpected for some people.

40 24 4 4

Why this is the result, in fact, sizeof was originally measured in the length of the type. And the array itself is actually implemented by pointers, so the actual measurement is actually the length of the pointer, as for the length of the measurement array can only be implemented in the scope of the array, once passed into other functions will be programmed with a pointer

Sometimes easy to use sometimes pit daddy's sizeof

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.