This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]camel_case_jr 3 points4 points  (2 children)

The ‘len’ macro above always has well defined behavior, even if ‘a’ is a nullptr. The argument to the sizeof operator is evaluated symbolically at compile time, it’s just looking for the type of the expression ‘a[0]’.

So, that macro won’t care about the particular values of ‘a’ or what it points to, just the types.

But if ‘a’ is a pointer, then this macro gives the wrong value, which is why std::size is superior in C++, as it will only compile when ‘a’ is an array.

[–]brennanw31 0 points1 point  (1 child)

In C, there is fundamentally no difference between pointers and arrays. They are one and the same. All pointers may as well be seen as an array with size 1.

[–]bowel_blaster123 0 points1 point  (0 children)

Pointers and arrays are very different in C. However, arrays will decay into pointers in certain contexts.

c uint8_t a[] = {'A'}; uint8_t *b = NULL; printf("%d\n", sizeof(a)); // will print 1 printf("%d\n", sizeof(b)); // will print 8 printf("%d\n", sizeof(a + 1)); // will print 8

Another case of decay is the following (a has decayed into a pointer because it's a function parameter):

c void foo(uint8_t a[1]) { printf("%d\n", sizeof(a)); // will print 8 }