gpt4 book ai didi

c - 我收到段错误 : 11

转载 作者:太空宇宙 更新时间:2023-11-04 06:57:43 25 4
gpt4 key购买 nike

我在放置“<<--”(第 9 行)符号的行中遇到错误。它没有任何编译错误,但在提供输入时显示“段错误:11”。我不知道出了什么问题。

输入:

3 3
1 1 1
2 2 2
3 1 5

代码:

#include <stdio.h>
#include <stdlib.h>

int comp (const void * x, const void * y)
{
int *a = *(int **)x;
int *b = *(int **)y;

//getting error here

if (a[0] == b[0]) // <<-- here
{
if (a[2] == b[2])
{
return -(a[1] - b[1]);
}
else
{
return a[2] - b[2];
}
}
else
{
return a[0] - b[0];
}
}

int main()
{
int n;
long long d;
scanf("%d %lld", &n, &d);

int t[n][3];
for (int i = 0; i < n; i++)
{
scanf ("%d %d %d", &t[i][0], &t[i][1], &t[i][2]);
}

printf("%lu\n", sizeof(t[0]));
qsort(t, n, sizeof(t[0]), comp);

for (int i = 0; i < n; ++i)
{
printf("%d-%d-%d\n", t[i][0], t[i][1], t[i][2]);
}
}

谁能帮我解决这个问题?

最佳答案

你的

int t[n][3];

数组实际上是由n int [3]类型的一维数组组成的一维数组。这些 int [3] 对象就是您要按

排序的对象
qsort(t, n, sizeof(t[0]), comp)

打电话。

因此,为了正确比较这些对象,您必须将比较回调的参数解释为指向 int [3] 对象的指针。同时,您当前的 comp 实现被编写为好像参数指向 int * 对象,这是不正确的。 int [3]int * 是两个截然不同的东西。

你可以这样做

int comp (const void * x, const void * y)
{
int (*a)[3] = x;
int (*b)[3] = y;

// And now compare the arrays by accessing them as `(*a)[1]`,
// `(*b)[2]` and so on
}

或者,您可以将 comp 序言代码编写为

int comp (const void * x, const void * y)
{
const int *a = *(int (*)[3]) x;
const int *b = *(int (*)[3]) y;

// And now compare the arrays by accessing them as `a[1]`,
// `b[2]` and so on, i.e. keep the rest of your code unchanged
}

这假定您的其余比较逻辑是正确的。请注意,通过将它们相减来比较 int 值是有风险的,因为它可能会溢出。

关于c - 我收到段错误 : 11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42030431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com