Context:
I programmed C on and off for about 2 years before I discovered that a[i] is just syntactic sugar for *(a + i) and therefore equivalent to * (i + a) and i[a] . My reality has been turned upside down, and many "AHA!" in the next few days of training and reading ("So, why arrays are always passed by reference!", etc.). Since then I have learned the equivalence of a pointer / array and kept it close to my heart, so imagine that it was a gross shock when I stumbled upon this thing called "Array decay". Here is a typical example:
the code:
#include <stdio.h> int Length(int*); int main () { int arr[100]; printf("Length of array: %d\n",(int)(sizeof(arr)/sizeof(arr[0]))); printf("Length of array: %d\n",Length(arr)); return 0; } int Length(int arr[]) { return sizeof(arr)/sizeof(arr[0]); }
Result:
Length of array: 100 Length of array: 2
Question:
So it turns out that C has some recognition of arrays after all! Basically, where an array is declared, the program can correctly report this size. Now I wonder how the syntax of the array is just the syntactic sugar for pointer operations (I previously assumed: all this). C actually has arrays, what are their limitations? An example shows that you can get their length as long as you are in the same function, what can you do for other interesting things? How far can you go before this error breaks up?
c arrays
TheIronKnuckle
source share