/* * array.c * * Computer Science 50, Fall 2011 * section4 * * Practice with treating arrays as pointers and navigating through * them with pointer arithmetic. */ #include #include int main(int argc, char* argv[]) { // ensures user entered one and only one command line arguments if(argc != 2) { printf("Usage: ./array size\n"); return 1; } // converts input to an integer int size = atoi(argv[1]); // ensures value is greater than 0 if(size <= 0) { printf("Please enter a positive integer.\n"); return 2; } // initalizes new array int* nums = malloc(sizeof(int) * size); // uses pointer arithmetic to store integers starting at 0 for(int i = 0; i < size; i++) *(nums + i) = i; // uses index notation to add 1 to each element for(int j = 0; j < size; j++) nums[j] += 1; // prints final array for(int k = 0; k < size; k++) printf("%d\n", nums[k]); // frees allocated memory free(nums); // success return 0; }