adding ft_strjoin_static

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

View File

@@ -54,6 +54,7 @@ SRCS = ft_memset.c \
ft_strncpy.c \
ft_strstr.c \
ft_strjoinfree.c \
ft_strjoin_static.c \
ft_strclr.c \
ft_strdel.c \
ft_strequ.c \

View File

@@ -49,6 +49,7 @@ char *ft_strdup(const char *s1);
char *ft_substr(char const *s, unsigned int start, size_t len);
char *ft_strjoin(char const *s1, char const *s2);
size_t ft_strjoin_static(char *dst, size_t dst_size, const char **srcs, size_t n);
char *ft_strtrim(char const *s1, char const *set);
char **ft_split(char const *s, char c);
char *ft_itoa(long int n);

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 ft_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;
}