How sizeof is implemented is exactly the same as the macro in the kernel

   0x00

   Many things are lacking when they are used too much. Insight, I feel that this is how it should be. This may be the old saying in China: the authorities are the fans. Today, I saw a student in the C group asking how to write the size of an array. Of course, I knocked sizeof involuntarily.

   0x04

sizeof is an operator not a function, but I suddenly thought, how does he implement that? If it is a string, you can also judge the '\0' at the end. How to judge the end of a piece of memory?


   0x08

Note that sizeof is an operator, not a function
Two neat macro implementations of sizeof.
sizeof for non-arrays:
#defne _sizeof(T) ( (size_t)((T*)0 + 1))
sizeof of the array:
#define array_sizeof(T)   ( (size_t)(&T+1)  - (size_t)(&T)  )
The principle is pointer arithmetic in c/c++.
Baidu looked at it like this,

The root of everything is pointer stride , I like to call it that, I think it's easier to understand, but most books don't address such a concept. Surely it's not over yet? In fact, it is not only that sizeof has two very famous macros in the linux kernel that rely on this principle, but the principle is also the same.








Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325443147&siteId=291194637