Skip to content

Instantly share code, notes, and snippets.

@zedshaw
Created January 4, 2015 19:07
Show Gist options
  • Save zedshaw/64b3fb6b7ed653852619 to your computer and use it in GitHub Desktop.
Save zedshaw/64b3fb6b7ed653852619 to your computer and use it in GitHub Desktop.
Demonstration of using a pointer to alter the operation of another function in C.
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#define MAXLINE 10 // in the book this is 1000
void safercopy(size_t to_length, char to[], size_t from_length, char from[])
{
int i = 0;
// if you're butthurt I put this if-statement here you can remove it to show me how to
// break the for-loop and make it run forever
if(to != NULL && from != NULL && (int)to_length > 0 && (int)from_length > 0) {
for(i = 0; i < to_length && i < from_length && from[i] != '\0'; i++) {
printf("i: %d, %x, %x\n", i, to[i], from[i]);
to[i] = from[i];
}
} else {
// normally you'd then have an error here, but I'm keeping the function call
// the same as in the book for the challenge
}
}
int main(int argc, char *argv[])
{
int offset = atoi(argv[1]);
char input[] = { 1, 1, 1 };
char *output = input + offset;
safercopy(3, output, 3, input);
return 0;
}
@mostlygeek
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment