Files
42_INT_01_libft/srcs/ft_strjoin_static.c
2026-05-07 11:46:03 +02:00

49 lines
1.5 KiB
C

#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 ft_strjoin_static(char *dst, size_t dst_size, const char **srcs, size_t n)
{
size_t total_len;
size_t i;
// Calculate total length needed
total_len = 0;
i = 0;
while (i < n)
{
total_len += ft_strlen(srcs[i]);
ft_printf("--ft_strlen(srcs[%i]):%i--", i, ft_strlen(srcs[i]));
i++;
}
ft_printf("{dst_size:%li,srcs[0]:%s,srcs[1]:%s,total_len:%i}", dst_size, srcs[0], srcs[1], total_len); // debug
// 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;
}