Skip to content

Instantly share code, notes, and snippets.

@vaalentin
Last active March 2, 2016 04:42
Show Gist options
  • Save vaalentin/244fe8aec61a8e9676a9 to your computer and use it in GitHub Desktop.
Save vaalentin/244fe8aec61a8e9676a9 to your computer and use it in GitHub Desktop.
C snippets
// 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);
#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