adding ft_strjoin_static

This commit is contained in:
hugogogo
2026-05-02 11:58:09 +02:00
parent f86c2cf5cb
commit a3810acb98
3 changed files with 44 additions and 0 deletions

42
srcs/ft_strjoin_static.c Normal file
View File

@@ -0,0 +1,42 @@
#include "libft.h"
/**
* Concatenates an array of strings into a pre-allocated destination buffer.
*
* @param dst Destination buffer.
* @param dst_size Size of the destination buffer (including space for null terminator).
* @param srcs Array of source strings to concatenate.
* @param n Number of strings in `srcs`.
* @return The total length of the concatenated string (excluding null terminator),
* or 0 if the buffer is too small.
* @note The caller must ensure `dst_size > 0`. If the buffer is too small,
* the function returns 0 and `dst` is set to an empty string.
*/
size_t strjoin_static(char *dst, size_t dst_size, const char **srcs, size_t n)
{
// Calculate total length needed
size_t total_len = 0;
for (size_t i = 0; i < n; i++)
{
total_len += ft_strlen(srcs[i]);
}
// Check if buffer is large enough (include space for '\0')
if (total_len + 1 > dst_size)
{
dst[0] = '\0';
return 0;
}
// Copy strings
char *ptr = dst;
for (size_t i = 0; i < n; i++)
{
size_t len = ft_strlen(srcs[i]);
ft_memcpy(ptr, srcs[i], len);
ptr += len;
}
*ptr = '\0';
return total_len;
}