/* Pointer example 3 */ #include #include #define MAX_SIZE 10 void init_array(int size, int a[]) { /* initialize elements[0..size-1] of array a Pre: 0 <= size < number of elements in a Post: none Side Effects: elements[0..size-1] of array a satisfy a[i] == i */ int i; for (i=0; i < size; i++ ) { a[i] = i; } } int* copy_array(int size, int a[]) { /* create a copy of the segment [0..size-1] of array argument a Note the convention of using int a[] in the argument list to indicate that the pointer is to an array, not just a single int. Pre: 0 < size <= number of elements in a sufficient memory for the copy to be allocated Post: copy_array(size, a) points to new array that is a copy of a[0] ... a[size-1] Side Effects: an region of memory of sufficient size to hold the copy is allocated. Future Conditions: the caller is responsible for freeing the copy later. */ int* p_copy; int i; p_copy = (int* ) calloc(size, sizeof(a[0]) ); /* if unable to allocate, a NULL pointer is returned */ if ( p_copy == NULL ) { fprintf(stderr, "copy_array could not allocate sufficient memory."); exit(1); } for ( i=0; i < size; i++ ) { p_copy[i] = a[i]; } return p_copy; } void main(int argc, char* argv[]) { int a[MAX_SIZE]; /* a is an array of MAX_SIZE ints */ int a_size = sizeof(a) / sizeof(a[0]); /* of this size */ int* b; /* b will point to an array */ int b_size; /* of this size */ int i; printf("\nThis is the output from %s:\n\n", argv[0]); printf("The address of a is %x\n", (int) a); printf("The number of elements in a is %d\n", a_size); printf("The size of an element of a is %d bytes\n", (int) sizeof(a[0]) ); printf("The number of bytes total in a is %d\n", (int) sizeof(a) ); init_array(a_size, a); printf("a contains:"); for (i=0; i < a_size; i++) { printf("%d ", a[i]); } printf("\n\n"); b_size = a_size -2; b = copy_array(b_size, a); printf("The address pointed to by b is %x\n", (int) b); printf("b contains:"); for (i=0; i < b_size; i++) { printf("%d ", *(b+i) ); } printf("\n"); }