#include #include int sum( int *nums, int array_len ) { int total = 0; for (int i = 0; i < array_len; i++) { total += nums[i]; } return total; } // Demonstrate pointer arithmetic and accessing elements of arrays. void array_demo1() { short i; int *x = (int *)malloc(sizeof(int) * 6); // int a[6]; printf( "x is pointing to %p\n", x ); printf( "x is stored at %p\n", &x ); printf( "a is stored at %p\n", &a ); for (i = 0; i < 6; i++) { x[i] = i*10; a[i] = i*10; } // pointer arithmetic // a + 1 is bytes beyond a because a is a pointer to ints and ints // are 4 bytes. This is a little on the complicated side until you // look at it like this: a[i] is equivalent to *(a+i), which means // go i elements beyond the beginning of the array and dereference // it. for (i = 0; i < 6; i++) { printf( "a[i] is at %p = %p\n", &(a[i]), a+i ); } for (i = 0; i < 6; i++) { printf( "x[i] is at %p = %p\n", &(x[i]), x+i ); } int t1 = sum( a, 6 ); int t2 = sum( x, 6 ); printf( "Sum of a's = %d, sum of x's = %d\n", t1, t2 ); } int main (int argc, char *argv[]) { array_demo1(); }