Created
December 30, 2021 01:01
-
-
Save opsJson/94060319487c9c14a22802e0d6983afd to your computer and use it in GitHub Desktop.
Allocate formatted strings without worrying about size.
This file contains hidden or 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 <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