Created
March 5, 2012 22:49
-
-
Save bnoordhuis/1981730 to your computer and use it in GitHub Desktop.
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 <stdlib.h> | |
#include <string.h> | |
static char **make_copy(int argc, char **argv) | |
{ | |
size_t strlen_sum; | |
char **argp; | |
char *data; | |
size_t len; | |
int i; | |
strlen_sum = 0; | |
for (i = 0; i < argc; i++) strlen_sum += strlen(argv[i]) + 1; | |
argp = malloc(sizeof(char *) * (argc + 1) + strlen_sum); | |
if (!argp) return NULL; | |
data = (char *) argp + sizeof(char *) * (argc + 1); | |
for (i = 0; i < argc; i++) { | |
argp[i] = data; | |
len = strlen(argv[i]) + 1; | |
memcpy(data, argv[i], len); | |
data += len; | |
} | |
argp[argc] = NULL; | |
return argp; | |
} | |
int main(int argc, char **argv) | |
{ | |
char **copy = make_copy(argc, argv); | |
int i; | |
for (i = 0; i < argc; i++) puts(copy[i]); | |
free(copy); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment