-
Notifications
You must be signed in to change notification settings - Fork 0
/
3-alloc_grid.c
54 lines (43 loc) · 967 Bytes
/
3-alloc_grid.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
/*
* File: 3-alloc_grid.c
*
* Author: Stanley O. Ajanaku
*/
#include "main.h"
#include <stdlib.h>
/**
* alloc_grid - returns a pointer to a 2 dimensional
* array of integers.
* @width: no of elements per subarray
* @height: Number of array elements
*
* Return: If successful a pointer to the 2d array,
* otherwise NULL
*/
int **alloc_grid(int width, int height)
{
int **twoD;
int hgt_index, wid_index;
if (width <= 0 || height <= 0)
return (NULL);
twoD = malloc(sizeof(int *) * height);
if (twoD == NULL)
return (NULL);
for (hgt_index = 0; hgt_index < height; hgt_index++)
{
twoD[hgt_index] = malloc(sizeof(int) * width);
if (twoD[hgt_index] == NULL)
{
for (; hgt_index >= 0; hgt_index--)
free(twoD[hgt_index]);
free(twoD);
return (NULL);
}
}
for (hgt_index = 0; hgt_index < height; hgt_index++)
{
for (wid_index = 0; wid_index < width; wid_index++)
twoD[hgt_index][wid_index] = 0;
}
return (twoD);
}