Skip to content

Instantly share code, notes, and snippets.

@mrdmnd
Created March 20, 2020 07:43
Show Gist options
  • Save mrdmnd/2edf044c56e1b0ac1c57839a10841b6c to your computer and use it in GitHub Desktop.
Save mrdmnd/2edf044c56e1b0ac1c57839a10841b6c to your computer and use it in GitHub Desktop.
Solutions to the first set of exercises on Pointers
#include "stdio.h"
#include "string.h"
// 6. (Implementation)
void memory_copy(void* to, const void* from, int n) {
// Need to cast from void to char so that pointer arithmetic works here.
const char* src = (const char *) from;
char* dest = (char *) to;
for (int i = 0; i < n; i++) {
*(dest++) = *(src++);
}
}
// 7. (Implementation)
void swap(char* a, char* b) {
char tmp = *a;
*a = *b;
*b = tmp;
}
// 8. (Implementation)
void permutations_aux(char* a, int l, int h) {
// Implement bell's algorithm: the permutations of a string ABCD are
// A + perms(BCD), B + perms(ACD), C + perms(ABD), D + perms(ABC)
if (l == h) {
printf("%s\n", a);
} else {
for (int i = l; i <= h; i++) {
swap( (a + l), (a + i) ); // swap a character
permutations_aux(a, l+1, h); // recurse
swap( (a + l), (a + i) ); // unswap
}
}
}
void permutations(char* s) {
// Suppose s is {'a', 'b', 'c', 'd', '\0'}.
// strlen(s) is 4.
// valid indices into this string are 0-3.
permutations_aux(s, 0, strlen(s)-1); // call our recursive method with both endpoints
}
int main() {
// 1.
/*
int result = 1;
int* result_ptr = &result;
(*result_ptr) *= 3;
result += 1;
printf("Result: %d\n", result);
*/
// 2. The original program:
/*
int main() {
const int array[3] = {25, 125, 625};
const int* array_ptr = array;
printf("The third element is %d\n", (*array_ptr+2));
*/
// The bug is that the dereference on array_ptr happens first (order of operations!)
// so we're actually deferencing the pointer to get an address,
// then adding two bytes offset to that address, which is not a valid location
// to interpret as an integer.
// 3.
/*
long double a;
char b[5];
printf("Long Double: %lu\n", sizeof(a)); // Prints 16
printf("Character Array: %lu\n", sizeof(b)); // Prints 5
*/
// 4.
// int* null_ptr = NULL;
// int contents = *null_ptr; // "Segmentation Fault: 11"
// My compiler says Segmentation Fault when I run this, so it's commented out here!
// 5.
// int values[3] = {0,1,2};
// int* value_ptr = values;
// *(value_ptr+3) = 999; // "Abort Trap: 6"
// Compiler says Abort Trap when I run this, so it's commented out here.
// 6. (Test code)
const char* src = "Comedy";
char dest[100];
memory_copy(dest, src, strlen(src)+1);
printf("%s\n", dest);
// 7. (Test code)
/*
char first = 'a';
char second = 'b';
swap(&first, &second);
printf("first: %c\n", first);
printf("second: %c\n", second);
*/
// 8. (Test code)
// char s[5] = "abcd";
// permutations(s);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment