-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2D_array.c
More file actions
67 lines (58 loc) · 1.71 KB
/
2D_array.c
File metadata and controls
67 lines (58 loc) · 1.71 KB
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
#include "alloc.h"
/**
* delete_2D_array - free a 2 dimensional array from memory.
* @array: a 2 dimensional array.
* @size: number of columns in the array, should be greater than 0.
* @free_row: pointer to a function that will be used to free the rows.
*
* Return: NULL always.
*/
void *delete_2D_array(
void **const array, intmax_t size, delete_func *free_row)
{
intmax_t a_i = 0;
if (!array || size < 1)
return (NULL);
for (a_i = 0; a_i < size; ++a_i)
{
free_row(array[a_i]);
array[a_i] = NULL;
}
return (_free(array));
}
/**
* dup_2D_array - duplicates a 2 dimensional array in memory.
* @array: the array to duplicate.
* @size: number of columns in the array, should be greater than 0.
* @copy_data: optional pointer to a function that will be used to duplicate
* the data, if not provided, array will contain pointers to the original data
* in the array.
* @free_data: optional pointer to a function that will be used to free data in
* the array in case of failure. If `copy_data` is provided this function must
* also be provided, otherwise no data duplication will occur.
*
* Return: the duplicated array on success, NULL on error.
*/
void **dup_2D_array(
void *const *const array, const intmax_t size,
dup_func *copy_data, delete_func *free_data)
{
intmax_t arr_i = 0;
void **array_dup = NULL;
if (!array || size < 1)
return (NULL);
array_dup = _calloc(size + 1, sizeof(*array_dup));
if (!array_dup)
return (NULL);
for (arr_i = 0; arr_i < size; ++arr_i)
{
array_dup[arr_i] = array[arr_i];
if (copy_data && free_data)
{
array_dup[arr_i] = copy_data(array[arr_i]);
if (!array_dup[arr_i])
return (delete_2D_array(array_dup, arr_i, free_data));
}
}
return (array_dup);
}