How to use memccpy to concatenating multiple strings in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
 
int main(void)
{
    char str[512] = "";
    char* end = str + sizeof str;
 
    // void* memccpy(void* restrict dest, const void* restrict src, int c, size_t count);
    // memccpy returns a pointer to the next byte in dest - after copy
 
    char* p = memccpy(str, "c, ", '\0', sizeof str - 1);
    
    if (p) {
        p = memccpy(p - 1, "c++, ", '\0', end - p);
    }

    if (p) {
        p = memccpy(p - 1, "java, ", '\0', end - p);
    }
    
    if (p) {
        p = memccpy(p - 1, "python ", '\0', end - p);
    }
    
    if (!p) {
        end[-1] = '\0';
    }
 
    puts(str); 
}



/*
run:

c, c++, java, python

*/

 



answered Apr 22, 2024 by avibootz

Related questions

1 answer 110 views
110 views asked Apr 22, 2024 by avibootz
2 answers 226 views
1 answer 222 views
2 answers 191 views
1 answer 159 views
...