/* pointers.c Jeff Ondich, 6 Jan 2022 Modified by Tanya Amert for Fall 2024 This program demonstrates some basic techniques using C pointers. The main() function consists of an odd collection of examples. Compile as usual: gcc -Wall -Werror -g -o pointers pointers.c Run with no command-line arguments: ./pointers */ #include #include #define BUFFER_SIZE 100 // Forward declarations of useful functions void swap_integers(int *a, int *b); void fill_with_alphabets(char *buffer, int buffer_size, int number_of_alphabets); // Demonstrates different ways of allocating and working with memory 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); *pointer = 'D'; printf("After: %s\n", animal); printf("\n"); return 0; } /* * Swaps the values stored at the two locations provided. * * Parameters: * - a: pointer to an integer (will get the value at b) * - b: pointer to an integer (will get the value at a) * * Returns: * - nothing; modifies the values stored in a and b */ void swap_integers(int *a, int *b) { if (a != NULL && b != NULL) { int saved_integer = *a; *a = *b; *b = saved_integer; } } /* * Fills the buffer with at most number_of_alphabets sets of * the characters a-z, up to buffer_size. The last character * is guaranteed to be a '\0', making the contents of buffer * a null-terminated string. * * Parameters: * - buffer: the memory address of the buffer to fill * - buffer_size: the maximum number of characters to fill * - number_of_alphabets: the maximum number of rounds of a-z * * Returns: * - nothing; modifies the contents of buffer */ void fill_with_alphabets(char *buffer, int buffer_size, int number_of_alphabets) { if (buffer != NULL) { int j = 0; for (int k = 0; k < number_of_alphabets; k++) { for (char ch = 'a'; ch <= 'z'; ch++) { if (j + 1 < BUFFER_SIZE) { buffer[j] = ch; j++; } } } buffer[j] = '\0'; } }