#include #define ASIZE 120 void print_array(int* arr, size_t size){ printf("["); for(size_t i = 0; i < size; i++) printf("%d, ", arr[i]); printf("\b\b]"); } char* format_array(int* arr, size_t size){ static char formatted_string[8196]; size_t current_end = 0; current_end += sprintf(formatted_string + current_end, "["); for(size_t i = 0; i < size; i++){ current_end += sprintf(formatted_string + current_end, "%d, ", arr[i]); if(current_end > 8196) return "The size specified results in a string that is too long for the static buffer that format_array uses to store the formatted string"; } current_end += sprintf(formatted_string + current_end, "\b\b]"); return formatted_string; } int main(){ int an_array[ASIZE]; // An array of 120 integers printf("sizeof(an_array): %d\n", sizeof(an_array)); // 120 * 4 bytes per int is 480 bytes // Common mistakes int *an_array_b[120]; // An array of 120 pointers to integers! printf("sizeof(an_array_b): %d\n", sizeof(an_array_b)); // 120 * 8 bytes per int* is 960 bytes // int an_array_c[]; // How big is it? Can't compile this, we don't know how big it is! // Since the line above asks for an allocation, we have to say the size int *an_array_d; // This is the address of an integer. //an_array_d[0] = 500; // This will compile, but cause a segmentation fault because there is no address in an_array_d // Here's a way to use an_array_d: an_array_d = an_array; // an_array refers to the address where our 120 integers are stored an_array_d[0] = 500; // This should work, because an_array_d is holding the address where an_array starts printf("an_array_d[0] = %d\n", an_array_d[0]); printf("an_array[0] = %d\n", an_array[0]); // Since an_array_d is holding the address of an_array, any change to an_array_d changes an_array printf("sizeof(an_array_d): %d\n", sizeof(an_array_d)); // an_array_d is a single memory address, so it's 8 bytes // Standard loop for(int i = 0; i < sizeof(an_array)/sizeof(an_array[0]); i++) an_array[i] = 3*i; for(int i = 0; i < ASIZE; i++) printf(" %d ", an_array_d[i]); printf("\n"); // Pointer arithmatic loop printf("an_array, but only the first 10: "); print_array(an_array, 10); printf("\n"); printf("an_array, shortened: %s\n", format_array(an_array, 5)); }