ft_range — Integer Array from Range
Allowed functions: malloc
It must allocate (with malloc()) an array of integers, fill it with consecutive values that begin at start and end at end (including start and end!), then return a pointer to the first value of the array.
int *ft_range(int start, int end);
Examples
- With
(1, 3)you will return an array containing 1, 2 and 3. - With
(-1, 2)you will return an array containing -1, 0, 1 and 2. - With
(0, 0)you will return an array containing 0. - With
(0, -3)you will return an array containing 0, -1, -2 and -3.
Solution
Download ft_range.c#include <stdlib.h>
int *ft_range(int start, int end) {
int step;
int len = 0;
int *arr;
if (start <= end) {
len = end - start + 1;
step = 1;
}
else {
len = start - end + 1;
step = -1;
}
arr = malloc(sizeof(int) * len);
if (!arr) {
return (NULL);
}
int i = 0;
while (i < len) {
arr[i] = start + (i * step);
i++;
}
return arr;
}
How It Works
Goal: Allocate and return an array of consecutive integers from start to end.
Approach: Determine the array length and step direction, allocate memory, then fill the array using the step.
Step by step:
- Compare
startandendto calculate the array length and setstepto1(ascending) or-1(descending). - Allocate an integer array of the computed length with
malloc. - Fill the array by setting
arr[i] = start + (i * step), which produces consecutive values in the correct direction.
Key concept: Dynamic memory allocation with malloc and handling both ascending and descending ranges using a step variable.