/* * ISA 563, Spring 2011 * Copyleft by Muhammad Abdulla */ #include /* * ptr_array.c -- Illustrates concepts related to pointer and array relationship in C. */ #define NELEMS(x) ((sizeof (x))/(sizeof ((x)[0]))) int main ( int argc, char *argv[] ) { int a[3]; int b[5]; int *p; int i; // pointer points to the first element of array p = &a[0]; // initialize arrays for ( i = 0; i < NELEMS(a); i++ ) { a[i] = 2*i; } for ( i = 0; i < NELEMS(b); i++ ) { b[i] = i*i; } for ( i = 0; i < NELEMS(a); i++ ) { printf("a[%d]: %2d p[%d]: %d\n", i, a[i], i, p[i]); } // can easily update pointer value with the address of another array p = b; for ( i = 0; i < NELEMS(b); i++ ) { printf("b[%d]: %2d p[%d]: %d\n", i, b[i], i, p[i]); } // Difference 1. Unlike pointers, we cannot assign to an array // a = b; // this will cause compilation error // Difference 2. sizeof(array) gives the total size of the array, sizeof(pointer) gives // gives the size of the pointer object itself, regardless of where its pointing to printf("sizeof(a): %d, sizeof(b): %d, sizeof(p): %d\n", sizeof(a), sizeof(b), sizeof(p)); return 0; }