0

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);


Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
이승훈
  • 43
  • 5

1 Answers1

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Thank you very much. By the way, i have one more question. I was told that if necessary, the array name is treated as a pointer. So what's the status of the array name when it's not needed? – 이승훈 Jul 30 '19 at 10:06
  • @이승훈 I have not understood the question. Please reread the quote from the C Standard. – Vlad from Moscow Jul 30 '19 at 10:08
  • The exceptions to the "automatic conversion" rule are: when the array is used as operand to the `sizeof` operator, when used as operand to the `&` (address of) operator, when used as a string literal to initialize an array, as [detailed in this answer](https://stackoverflow.com/a/17753057/25324). – pmg Jul 30 '19 at 10:10
  • @이승훈 *if necessary, the array name is treated as a pointer* -- Not really. An array is not a pointer, and an array name is not a pointer, either. What happens is that when you use an array in an expression, in a context where it seems like you might be trying to use the "value" of the array, you don't get the whole array -- what you get is a pointer to the array's first element, as if you had written `&array[0]`. – Steve Summit Jul 30 '19 at 10:32
  • I read the document that you uploaded. An array is not a pointer, nor vice versa, and an array name is not a pointer. Then, is it correct that array name is a ```non-modifable l-value```? – 이승훈 Jul 30 '19 at 11:32
  • @이승훈 Yes it is a non-modifiable lvalue. – Vlad from Moscow Jul 30 '19 at 11:35
  • @Vlad from Moscow OK, I understand. Really appreciate it. – 이승훈 Jul 30 '19 at 11:40