I've been trying to do the following Kata on Codewars:
The objective is to return all pairs of integers from a given array of integers that have a difference of 2.
The result array should be sorted in ascending order of values.
Assume there are no duplicate integers in the array. The order of the integers in the input array should not matter.
This is my solution, but its crashing with SIGSEGV (11). Invalid memory access.
Can someone please help?
#include <stdlib.h>
typedef struct Integer_Pair {
int a;
int b;
} pair;
// N.B. assign the size of the return array to the pointer *z
size_t twos_difference(size_t n, const int array[n], size_t *z) {
pair* tot = malloc(sizeof(pair));
if (tot == NULL)
return 0;
int temp[n];
int val;
// Counter for tot
int c = 0;
// Copy array elements in temp for later comparison
for (size_t i = 0; i < n; i++)
{
temp[i] = array[i];
}
// Sort array and store in ascending order into temp
for (size_t i = 0; i < n; i++)
{
for (size_t j = i + 1; j < n; j++)
{
if (temp[i] > temp[j])
{
val = temp[i];
temp[i] = temp[j];
temp[j] = val;
}
}
}
// If difference between 2 numbers is 2, store in tot
for (size_t i = 0; i < n; i++)
{
for (size_t j = 0; j < n; j++)
{
if (temp[i] - array[j] == -2)
{
tot[c].a = array[i];
tot[c].b = temp[j];
c++;
}
}
}
// Copy number of pairs with difference of 2 in tot
*z = c;
return *z;
free(tot);
}