Analysis of SIZEOF misunderstood in C and C++

  • 2020-04-02 01:07:01
  • OfStack

1: is sizeof a function?
2: what's the difference between sizeof and strlen?
3: what is the value of sizeof(int)(*p)?

int a[10];
   sizeof(a);//How much is?
   sizeof(a[10]);//How much is?
   void f(int a[10])
   {
     cout<<sizeof(a)<<endl;// value How much is?
   }
View Code

Answer:
1: to the first question, sizeof is not a function, but it is a language with a built-in keywords, not letter you try sizeof 4 and sizeof (int), the print results are 4, if it is a function, must be combined with parentheses, namely however didn't add parentheses, so what is the sizeof? :), if you still don't believe, you can find any check a C + + / C programming language book, sizeof is one of 32 keyword, if not, you will change the book:)
Even if it is a keyword, why do we need parentheses? You can try the sizeof int and sizeof (int), the first will compile the pass, and the second is to compile, think of the rules of the C/C + + language, can only add signed before int. Unsigned, auto, const, volative, used to modify the variable way of storage, but did not mention the front can add sizeof yo, if adding sizeof said what storage:)

2: sizeof keyword, strlen is a standard C library functions, used to calculate the length of the string, char * STR = "abacd", sizeof STR and strlen (STR), compile once, look at the results:), a result is 4, a result is 5, the result is 4 because a pointer of 4 bytes, the result of 5 is because long string abacd just five characters, no explanation

3: what is the value of sizeof(int)(*p)? This with the help of 1, has been analyzed in great detail, in fact, is to take the value of *p, the data into an int, and then measure the number of bytes of memory occupied by the data, it is clear that an int data accounts for 4 bytes

int a[10];
sizeof(a) How much is the ?

What is the measurement? The result is 40. Sizeof here measures the sizeof an array

int a[10];
sizeof(a[10]) How much is the ?

A careful person will find that a[10] has crossed the line, and using sizeof here will not cause an error because it is a run-time exception that the compiler does not check. At this point, the compiler thinks that a[10] is an integer variable in the array, and the result is of course 4

void f(int a[10])
   {
     cout<<sizeof(a)<<endl;//What is the value?
   }

What is the value of this output up here? You can write a program to try it out, and it turns out to be 4. Why? Because the C/C++ language states that functions cannot take an array as an argument or return a value, and that the above functions will be converted to in the actual compilation process

void f(int *a)
   {
     cout<<sizeof(a)<<endl;//What is the value?
   }

Because a is a pointer to an integer, it's also obvious that it's going to be 4

Related articles: