-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3-alloc_grid.c
More file actions
executable file
·69 lines (56 loc) · 972 Bytes
/
3-alloc_grid.c
File metadata and controls
executable file
·69 lines (56 loc) · 972 Bytes
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
69
#include "main.h"
#include <stdio.h>
#include <stdlib.h>
/**
* alloc_array - allocate an array
*
* @size: size of an array
*
* Return: {NULL} if size = 0 or failure, {pointer} otherwise
*/
int *alloc_array(int size)
{
int *arr = malloc(size * sizeof(int));
if (!size || !arr)
return (NULL);
while (size--)
arr[size] = 0;
return (arr);
}
/**
* alloc_grid - allocate and 2d array
*
* @width: number of colums
* @height: number of rows
*
* Return:{NULL} if failure, otherwise {pointer to grid}
*/
int **alloc_grid(int width, int height)
{
register int i, flag;
int **grid;
grid = malloc(height * sizeof(int *));
if (height <= 0 || width <= 0 || !grid)
return (NULL);
flag = 1;
for (i = 0; i < height; i++)
{
grid[i] = alloc_array(width);
if (!grid[i])
{
flag = 0;
break;
}
}
while (!flag && i--)
{
free(grid[i]);
grid[i] = NULL;
}
if (!flag)
{
free(*grid);
grid = NULL;
}
return (grid);
}