Skip to content

Instantly share code, notes, and snippets.

@MrDave1999
Last active December 14, 2021 15:00
Show Gist options
  • Save MrDave1999/9007d11c9780f57f7fe07a29057d8852 to your computer and use it in GitHub Desktop.
Save MrDave1999/9007d11c9780f57f7fe07a29057d8852 to your computer and use it in GitHub Desktop.
Implementing a strcpy so that you can copy multiple strings.
#include <stdio.h>
#include <stdarg.h>
#define STRCOPY(destination, num, ...) strcopy(destination, num, __VA_ARGS__, NULL)
char* strcopy(char*, size_t, ...);
int main(void)
{
char dest[10 + 1];
printf("%s\n", STRCOPY(dest, sizeof dest, "Hello", "World"));
printf("%s\n", STRCOPY(dest, sizeof dest, "Hello", "World!"));
printf("%s\n", STRCOPY(dest, sizeof dest, "Hello"));
printf("%s\n", STRCOPY(dest, sizeof dest, "Hello", "World", "alvarez!"));
printf("%s\n", STRCOPY(dest, sizeof dest, "Hello", "World!!"));
printf("%s\n", STRCOPY(dest, sizeof dest, "Hello", ""));
getchar();
return 0;
}
char* strcopy(char* destination, size_t num, ...)
{
va_list list;
va_start(list, num);
num -= 1;
size_t i = 0;
char* source = va_arg(list, char*);
while(source != NULL && i < num)
{
for(size_t j = 0; source[j] != '\0' && i < num; ++j, ++i)
destination[i] = source[j];
source = va_arg(list, char*);
}
destination[i] = '\0';
va_end(list);
return destination;
}
#include <stdio.h>
#include <stdarg.h>
#define STRCOPY(destination, num, ...) strcopy(destination, num, __VA_ARGS__, NULL)
char* strcopy(char*, size_t, ...);
int main(void)
{
char dest[10 + 1];
printf("%s\n", STRCOPY(dest, sizeof dest, "Hello", "World"));
printf("%s\n", STRCOPY(dest, sizeof dest, "Hello", "World!"));
printf("%s\n", STRCOPY(dest, sizeof dest, "Hello"));
printf("%s\n", STRCOPY(dest, sizeof dest, "Hello", "World", "alvarez!"));
printf("%s\n", STRCOPY(dest, sizeof dest, "Hello", "World!!"));
printf("%s\n", STRCOPY(dest, sizeof dest, "Hello", ""));
getchar();
return 0;
}
char* strcopy(char* destination, size_t num, ...)
{
va_list list;
va_start(list, num);
num -= 1;
char* dest = destination;
char* source = va_arg(list, char*);
while(source != NULL && num != 0)
{
for(; *source != '\0' && num != 0; ++source, ++dest, --num)
*dest = *source;
source = va_arg(list, char*);
}
*dest = '\0';
va_end(list);
return destination;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment