/** * Array in C * array_demo.c */ #include #include int main () { // array on the stack int i; int a[5]; for (i = 0; i < 5; i++) { a[i] = i * 10; } for (i = 0; i < 5; i++) { printf("%d at %p\n", a[i], &(a[i]) ); } // array on the heap int *b; b = malloc(5 * sizeof(int)); for (i = 0; i < 5; i++) { *(b+i) = i * 100; // b[i] = i*100; // equivalent } for (i = 0; i < 5; i++) { printf("%d at %p\n", *(b+i), b+i); // printf("%d at %p\n", *(b+i), &(b[i]) ); } // There is a difference between arrays on the stack and arrays on the heap // but it is subtle. // Both are addresses, but the sizes are different. // On the stack, the sizeof is the number of total bytes (so it // contains information about the length) printf( "Is a an address? Yes if %p==%p, number of bytes for a = %lu\n", a, &(a[0]), sizeof(a) ); printf( "Is b an address? Yes if %p==%p, number of bytes for b = %lu\n", a, &(a[0]), sizeof(b) ); free(b); long int*c; c = malloc(5 * sizeof(long int)); for (i = 0; i < 5; i++) { *(c+i) = i * 1000; } for (i = 0; i < 5; i++) { printf("%ld at %p\n", *(c+i), c+i); } printf( "opposites? %p %p\n", &*c, c ); free(c); return 0; }