C语言 Difference of 2 - SIGSEGV (11) [Codewars]



我一直在尝试在Codewars上执行以下Kata:

目标是返回给定整数数组中差值为2的所有整数对。

结果数组应按值的升序进行排序。

假设数组中没有重复的整数。输入数组中整数的顺序应该无关紧要。

这是我的解决方案,但它与SIGSEGV (11). Invalid memory access.一起崩溃

有人能帮忙吗?

#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);
}

pair*tot=malloc(sizeof(pair((;

在这里,您只分配了一个pair实例。

tot[c].a=数组[i]
tot[c].b=温度[j];

在这里,您正在访问多个pair实例

你需要分配更多的元素。pair* tot = malloc(n*sizeof(pair));

pair* tot = malloc(sizeof(pair));
应更改为
pair* tot = (pair *)malloc(sizeof(pair));
,并且您的返回语句
if (tot == NULL)
应该将该语句放在同一行或缩进:
if (tot == NULL) return 0;
第一个更改将修复SIGSEGV异常,第二个更改只是良好的编码实践,使代码更可读。

最新更新