ft_rrange — Reverse Integer Range
Allowed functions: malloc
It must allocate (with malloc()) an array of integers, fill it with consecutive values that begin at end and end at start (including start and end!), then return a pointer to the first value of the array.
int *ft_rrange(int start, int end);
Examples
- With
(1, 3)you will return an array containing 3, 2 and 1. - With
(-1, 2)you will return an array containing 2, 1, 0 and -1. - With
(0, 0)you will return an array containing 0. - With
(0, -3)you will return an array containing -3, -2, -1 and 0.
Solution
Download ft_rrange.c#include <stdlib.h>
int *ft_rrange(int start, int end) {
int len, step;
if (start <= end) {
len = end - start + 1;
step = -1;
} else {
len = start - end + 1;
step = 1;
}
int *arr = malloc(sizeof(int) * len);
if (!arr)
return NULL;
int i = 0;
while (i < len) {
arr[i] = end + (i * step);
i++;
}
return arr;
}
How It Works
Goal: Allocate and return an array of consecutive integers from end to start (reverse of ft_range).
Approach: Calculate length and a reversed step direction, allocate memory, then fill starting from end.
Step by step:
- Compute the array length from the difference between
startandend. - Set
stepto-1whenstart <= end(filling backwards fromenddown) or1otherwise. - Allocate the array with
mallocand fill it usingarr[i] = end + (i * step).
Key concept: Reverse filling logic — the step direction is inverted compared to ft_range, so the array starts at end and moves toward start.