#include int main(int argc, char** argv) { // Basic example of array with initialization int basic[20] = { 1, 2, 3, 4, 5}; // Note: rest will be set to zero printf("Basic array: { "); int index; for (index = 0; index < 20 ; index++) { printf(" %d,", basic[index]); } printf("}\n"); int size = 10; int c[size]; // Note: using a variable as the array size is a recent feature // The following is wrong!!! c[12] = 23; // BUG! Array out-of-bounds printf("%d\n",c[12]); // BUG! Array out-of-bounds // The above are bugs! But they may remain silent. // The compiler does not check array bounds. // There are no explicit runtime checks either. // If you are lucky, you will get a segmentation fault // Often, out-of-bounds errors can go undetected for a long time // To avoid bugs, we must remember the size of the array // and always check bounds explicitly // An array is just a group of memory locations int i; for (i = size-1; i >= 0 ; i--) { printf("%p\n",&c[i]); } // The name of the array corresponds to the address of the // beginning of the array printf("Array name: %p\n", c); // Two methods to access and update elements of the array for (i = size-1; i >= 0; i--) { c[i] = 2*i; printf("c[i] is %d ", c[i]); // Preferred, more readable printf("*(c+i) is %d\n", *(c+i)); // Possible } // We can create additional pointers to the array // This can be useful. For example, if we want to sort the elements of the array int *p = c; printf("Test %d\n", *p); p++; printf("Test %d\n", *p); return 0; }