Page 47 - C-Language
P. 47

The same would be true even if a dimension were given. This is possible because arrays cannot
        ever be actual arguments to functions (they decay to pointers when they appear in function call
        expressions), and it can be viewed as mnemonic.


        It is a very common error to attempt to determine array size from a pointer, which cannot work. DO
        NOT DO THIS:


         int BAD_get_last(int input[]) {
             /* INCORRECTLY COMPUTES THE LENGTH OF THE ARRAY INTO WHICH input POINTS: */
             size_t length = sizeof(input) / sizeof(input[0]));

             return input[length - 1];  /* Oops -- not the droid we are looking for */
         }



        In fact, that particular error is so common that some compilers recognize it and warn about it. clang
        , for instance, will emit the following warning:


         warning: sizeof on array function parameter will return size of 'int *' instead of 'int []' [-
         Wsizeof-array-argument]
                 int length = sizeof(input) / sizeof(input[0]);
                                    ^
         note: declared here
         int BAD_get_last(int input[])
                              ^



        Setting values in arrays


        Accessing array values is generally done through square brackets:


         int val;
         int array[10];

         /* Setting the value of the fifth element to 5: */
         array[4] = 5;

         /* The above is equal to: */
         *(array + 4) = 5;

         /* Reading the value of the fifth element: */
         val = array[4];


        As a side effect of the operands to the + operator being exchangeable (--> commutative law) the
        following is equivalent:


         *(array + 4) = 5;
         *(4 + array) = 5;


        so as well the next statements are equivalent:


         array[4] = 5;
         4[array] = 5; /* Weird but valid C ... */





        https://riptutorial.com/                                                                               23
   42   43   44   45   46   47   48   49   50   51   52