Forcing a decay of the array (for the lack of better title)

耗尽温柔 提交于 2020-05-12 02:24:11

问题


Inspired by this question: How does *(&arr + 1) - arr give the length in elements of array arr?

The following code will calculate the length of an array, albeit invoking undefined behavior:

int  arr[] = {5, 8, 1, 3, 6};
size_t len = *(&arr + 1) - &arr[0]; // len is 5

I believe, that by dereferencing the (&arr + 1) we are triggering undefined behavior. However, the only reason we are doing this is to immediately decay the result into int*, pointing to one element after the last one in original array. Since we do not dereference this pointer, we are well in defined zone.

The question thus is following: is there a way to decay into int* without dereferencing the undereferencable pointer and staying defined?

P.S. Mandatory disclaimer: yes, I can calculate the size of an array with sizeof operator and division. This is not the point of the question.

EDIT: I am now less sure that the indirection itself is undefined. I have found http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#232 and from it looks it seems like there was an attempt to legalize the indirection per se, but I was not able to find any wording to this effect in actual standard.

来源:https://stackoverflow.com/questions/61238781/forcing-a-decay-of-the-array-for-the-lack-of-better-title

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!