Last active
March 2, 2016 04:42
-
-
Save vaalentin/244fe8aec61a8e9676a9 to your computer and use it in GitHub Desktop.
C snippets
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
// create | |
char** arr = (char**) malloc(10 * sizeof(char**)); | |
for(int i = 0; i < 10; ++i) { | |
*(arr + i) = (char*) malloc(sizeof(char*) * 4); | |
strcpy(*(arr + i), "test"); | |
} | |
// use | |
for(int i = 0; i < 10; ++i) { | |
printf("%s\n", *(arr + i)); | |
} | |
// free | |
for(int i = 0; i < 10; ++i) { | |
free(*(arr + i)); | |
} | |
free(arr); |
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 <string.h> | |
char* concat(char* a, char* b) { | |
// + 1 for '\0' | |
char* s = (char*) malloc(sizeof(a) + sizeof(b) + 1); | |
if(s == NULL) { | |
// malloc error | |
} | |
// strcat needs '\0' to copy after. | |
// s being uninitialized, we can either set it by hand at [0] or use strcpy. | |
// | |
// s[0] = '\0'; | |
// strcat(s, a); | |
// strcat(s, b); | |
// | |
// strcpy(s, a); | |
// strcat(s, b); | |
*s = '\0'; | |
strcat(s, a); | |
strcat(s, b); | |
return s; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment