Skip to content

Instantly share code, notes, and snippets.

@belak
Last active August 29, 2015 14:06
Show Gist options
  • Select an option

  • Save belak/ee01d757788c9f45a1d2 to your computer and use it in GitHub Desktop.

Select an option

Save belak/ee01d757788c9f45a1d2 to your computer and use it in GitHub Desktop.
Random C string utils
// NOTE: _GNU_SOURCE is required for this to work because of asprintf
#define _GNU_SOURCE
#include <stdarg.h>
#include <stdio.h>
// This function allocates a string, prints the formatted version to it and uses write to print it to stdout.
void waprintf(const char *fmt, ...) {
va_list args;
char *str = NULL;
va_start(args, fmt);
vasprintf(&str, fmt, args);
va_end(args);
write(1, str, strlen(str) * sizeof(char));
free(str);
}
#define _GNU_SOURCE
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
// This is like atoi but the other direction
// NOTE: the string will be invalid on the next call to itoa
char ibuf[32];
char *itoa(int x) {
return snprintf(&ibuf, 31, "%d", x);
}
// This function converts an array of ints into a string.
char *array_to_string(int *arr, int count) {
int i;
int size = 1;
char *data = malloc(sizeof(char) * size);
data[0] = '\0';
for (i = 0; i < count; i++) {
char *temp = itoa(arr[i]);
size += strlen(temp) + 2;
data = realloc(data, sizeof(char) * size);
strcat(data, " ");
strcat(data, temp);
}
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment