Created
January 4, 2015 19:07
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
for posterity: https://news.ycombinator.com/item?id=8835529