/* 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 #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"); printf("===== game 5: string copy with pointer arithmetic =====\n"); char creature[BUFFER_SIZE] = "capybara"; char beast[BUFFER_SIZE] = "null beast"; printf("Before copying: %s (creature), %s (beast)\n", creature, beast); char *source_pointer = creature; char *destination_pointer = beast; while (*source_pointer != '\0') { *destination_pointer = *source_pointer; destination_pointer++; source_pointer++; } *destination_pointer = '\0'; printf("After copying: %s (creature), %s (beast)\n", creature, beast); printf("BUT WATCH OUT! DID THESE POINTERS OVERFLOW THE BUFFER? HOW WOULD WE KNOW?\n"); printf("\n"); printf("===== game 6: same as game 5, but with terse code like pros sometimes do it =====\n"); strncpy(creature, "capybara", BUFFER_SIZE); strncpy(beast, "null beast", BUFFER_SIZE); printf("Before copying: %s (creature), %s (beast)\n", creature, beast); char *p = creature; char *q = beast; while (*p != '\0') { *q++ = *p++; } *q = '\0'; printf("After copying: %s (creature), %s (beast)\n", creature, beast); printf("BUT WATCH OUT! DID THESE POINTERS OVERFLOW THE BUFFER? HOW WOULD WE KNOW?\n"); 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'; } }