/* pointers.c Jeff Ondich, 6 Jan 2022 This program demonstrates some basic techniques using C pointers. main() consists of an odd collection of examples, best consumed with the guidance of the author (that is, I'll walk through this program and its intentions in class) */ #include #include #define BUFFER_SIZE 100 void swap_integers(int *a, int *b); void fill_with_alphabets(char *buffer, int buffer_size, int number_of_alphabets); int main(int argc, char *argv[]) { printf("===== game 1: passing parameters by address =====\n"); int x = 62; int y = 35; printf("Before swap: x = %d, y = %d\n", x, y); swap_integers(&x, &y); printf("After swap: x = %d, y = %d\n", x, y); printf("\n"); printf("===== game 2: statically allocated memory =====\n"); char buffer[BUFFER_SIZE]; fill_with_alphabets(buffer, BUFFER_SIZE, 3); printf("Here are 3 alphabets: %s\n", buffer); printf("\n"); printf("===== game 3: dynamically allocated memory =====\n"); char *other_buffer; other_buffer = (char *)malloc(BUFFER_SIZE * sizeof(char)); fill_with_alphabets(other_buffer, BUFFER_SIZE, 3); printf("Here are 3 alphabets: %s\n", other_buffer); free(other_buffer); printf("\n"); printf("===== game 4: array index arithmetic =====\n"); char animal[BUFFER_SIZE] = "WARTHOG"; printf("Before: %s\n", animal); char *pointer = (char *)(animal + 4 * sizeof(char)); *pointer = 'D'; printf("After: %s\n", animal); printf("\n"); return 0; } void swap_integers(int *a, int *b) { if (a != NULL && b != NULL) { int saved_integer = *a; *a = *b; *b = saved_integer; } } void fill_with_alphabets(char *buffer, int buffer_size, int number_of_alphabets) { if (buffer != NULL) { int j = 0; for (int k = 0; k < 3; k++) { for (char ch = 'a'; ch <= 'z'; ch++) { if (j + 1 < BUFFER_SIZE) { buffer[j] = ch; j++; } } } buffer[j] = '\0'; } }