我收到分段错误:11
I am getting Segmentation fault: 11
我在放置“<<--
”(第 9 行)符号的行中遇到错误。它没有任何编译错误,但在提供输入时显示 "Segmentation fault: 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
值是有风险的,因为它可能会溢出。
我在放置“<<--
”(第 9 行)符号的行中遇到错误。它没有任何编译错误,但在提供输入时显示 "Segmentation fault: 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
值是有风险的,因为它可能会溢出。