Can “sizeof(arr[0])” lead to undefined behavior?
问题 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); This pattern applies to static arrays and auto arrays of constant size. It also applies to variable length arrays in C99. I want to apply similar idea for figuring out dynamic array size in bytes: size_t known_len = 10; int *ptr = malloc(known_len * sizeof(int)); size_t size = known_len * sizeof(ptr[0]); assert(size == known_len * sizeof(int)); This is nicer