what is array decay in c and when it happen?

折月煮酒 提交于 2021-02-11 12:19:26

问题


I am currently studying C language. I wonder what 'array decaying' means, and when it happens.

And I wonder if the two variables below are interpreted in the same way.


char(*zippo)[2] = NULL;
char zippo2[4][2];

zippo = (char(*)[2])malloc(sizeof(char[2]) * 4);



回答1:


From the C Standard (6.3.2.1 Lvalues, arrays, and function designators)

3 Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.

The two variables below

char(*zippo)[2] = NULL;
char zippo2[4][2];

have different types. The first one is a pointer to an object of the type char[2]. The second one is a two-dimensional array with four elements of the type char[2].

When the array zippo2 is used in expression except the expressions listed in the quote (as for example using it with the sizeof operator) then its designator is implicitly converted to pointer to its first element and has the same type as the variable zippo.



来源:https://stackoverflow.com/questions/57268963/what-is-array-decay-in-c-and-when-it-happen

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