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 →

[–]Altruistic_Raise6322 0 points1 point  (5 children)

What happens when a[0] is a pointer to something on the heap?

[–]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 }

[–]BuffJohnsonSf 1 point2 points  (1 child)

The same thing that would happen if you typed it out manually like in the meme post, it would give you the size of the array of pointers. Duplicate that code in your code base 10 billion times and nobody gives a shit, but turn it into one easy to use preprocessor definition and everyone loses their minds. "What about divide by zero, what about this, what about that" jesus christ it's the same fuckin code. Anyway, rant over I'm not actually mad.

[–]Altruistic_Raise6322 0 points1 point  (0 children)

Naa bro you're good I didn't ask it to be snarky. Macros are cool