Skip to content

Instantly share code, notes, and snippets.

@opsJson
Created December 30, 2021 01:01
Show Gist options
  • Select an option

  • Save opsJson/94060319487c9c14a22802e0d6983afd to your computer and use it in GitHub Desktop.

Select an option

Save opsJson/94060319487c9c14a22802e0d6983afd to your computer and use it in GitHub Desktop.
Allocate formatted strings without worrying about size.
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
size_t counter(char *str) {
size_t commas = 0;
int string = 0;
while (*str) {
//escape commas inside string;
if (*str == '"' && *(str - 1) != '\\') string = !string;
//count commas
if (string == 0)
if (*str == ',') commas++;
str++;
}
return commas+1;
}
char* __countstr__(char *format, size_t count, ...) {
int i;
char *str;
va_list args;
size_t length;
va_start(args, count);
for (i=0,length=0; i<count; i++)
length += strlen(va_arg(args, char*));
str = (char*)malloc((sizeof(char) * length)
+ (sizeof(char) * strlen(format))
+ 1);
return str;
}
char* makestr(char *ptr, char *format, ...) {}
#define makestr(str, format, ...) \
str = __countstr__(format, counter(#__VA_ARGS__), __VA_ARGS__); \
sprintf(str, format, __VA_ARGS__);
/*///////////////////////////////////
Testing:
///////////////////////////////////*/
int main() {
char *ptr;
makestr(ptr, "{\"foo\":%s}", "123");
printf("%s\n", ptr);
free(ptr);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment