Can “sizeof(arr[0])” lead to undefined behavior?

后端 未结 5 1421
长发绾君心
长发绾君心 2020-12-31 05:31

There is a well known pattern of figuring out array length:

int arr[10]; 
size_t len = sizeof(arr) / sizeof(arr[0]); 
assert(len == 10); 

T

5条回答
  •  臣服心动
    2020-12-31 05:37

    As an expression (not a declaration), ptr[0] is identical to *ptr.

    As long as the type of ptr is known and it is not pointing to void, sizeof is guaranteed to work on sizeof(*ptr) as well as sizeof(ptr[0]).

提交回复
热议问题