-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstring_array_handlers.c
68 lines (55 loc) · 1.38 KB
/
string_array_handlers.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include "shell.h"
/**
* duplicate_str_array - duplicate a string array
* @original: the original string
*
* Return: the duplicate string on success, else NULL if it fails
*/
char **duplicate_str_array(char **original)
{
size_t size, i;
char **duplicate;
if (original == NULL)
return (NULL);
size = 0;
while (original[size] != NULL)
size++;
duplicate = malloc((size + 1) * sizeof(char *));
if (duplicate == NULL)
return (NULL);
for (i = 0; i < size; i++)
{
duplicate[i] = _strdup(original[i]);
if (duplicate[i] == NULL)
{
free_str(&duplicate);
return (NULL);
}
}
duplicate[size] = NULL;
return (duplicate);
}
/**
* concatenate_arrays - appends the contents of one string array to another
* @dest: a pointer to the destination string array
* @src: the source string array (where to copy from)
*/
void concatenate_arrays(char ***dest, char **src)
{
int i, src_length = 0, dest_length = 0;
if (src == NULL)
return; /* there's nothing concatenate */
while ((*dest)[dest_length] != NULL)
dest_length++;
while (src[src_length] != NULL)
src_length++;
*dest = realloc(*dest, (dest_length + src_length + 1) * sizeof(char *));
if (*dest == NULL)
return; /* memory allocation failed */
for (i = 0; i < src_length; i++)
{
(*dest)[dest_length + i] = _strdup(src[i]);
}
/* null terminate the string array */
(*dest)[dest_length + src_length] = NULL;
}