【发布时间】:2014-08-02 22:45:44
【问题描述】:
我想编写一个程序,通过 qsort 函数按字典顺序对矩阵的行进行排序。由于比较函数需要知道每一行的大小,并且没有办法传递第三个参数,所以我将每一行都设为一个包含行大小的 ROW 结构。然后将问题简化为按字典顺序对结构进行排序。
我编写了默认构造函数、复制 cnostructor 和析构函数。我重载了赋值运算符。
我在VS2010上运行程序时,偶尔会报如下错误。当我在 Linux 中使用 g++ 运行它时,它可能会将某些元素修改为意外状态或在 core dumped 中运行。
谁能告诉我应该在哪里修改代码?谢谢
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
using namespace std;
struct ROW
{
int *ptr;
int L;
ROW();
ROW(ROW &obj);
~ROW();
ROW& operator = (const ROW& obj);
};
ROW::ROW()
{
ptr = 0;
L = 0;
}
ROW::ROW(ROW &obj)
{
L = obj.L;
ptr = new int [L];
memcpy(ptr,obj.ptr,L*sizeof(int));
}
ROW::~ROW()
{
if (ptr)
delete [] ptr;
ptr = NULL;
}
ROW& ROW::operator = (const ROW& obj)
{
if (this != &obj)
{
//this->ptr = obj.ptr;
if (ptr)
delete [] ptr;
ptr = new int [L];
memcpy(ptr,obj.ptr,L*sizeof(int));
}
return *this;
}
int MyCMP(const void *a, const void *b)
{
ROW *L = (ROW*)a;
ROW *R = (ROW*)b;
for (int i=0; i < (L->L); i++)
if ((L->ptr[i]) < (R->ptr[i]))
return -1;
else if ((L->ptr[i]) > (R->ptr[i]))
return 1;
return 0;
}
int main()
{
srand(time(0));
int R_size = 23;
int R = 7;
ROW* A = new ROW[R];
//scanf("%d %d",&R, &R_size);
R = rand()%20+1;
R_size = rand()%30+1;
printf("Row: %d, Column: %d.\n",R,R_size);
for (int i=0; i<R; i++)
{
A[i].ptr = new int [R_size];
A[i].L = R_size;
for (int j=0; j<R_size; j++)
{
A[i].ptr[j] = rand()%100;
printf("%d ",A[i].ptr[j]);
}
printf("\n");
}
printf("After sorting\n");
qsort(A,R,sizeof(ROW),MyCMP);
for (int i=0; i<R; i++)
{
for (int j=0; j<R_size; j++)
printf("%d ",A[i].ptr[j]);
printf("\n");
}
/*
for (int i=0; i<R; i++)
{
if (A[i].ptr)
{
delete [] (A[i].ptr);
A[i].ptr = NULL;
}
}
delete [] A;
*/
return 0;
}
WINDOWS error
TestArraySort.exe has stopped working
windows can check online for a solution to the problem.
Problem Event Name: APPCRASH
Application Name: TestArraySort.exe
Application Version: 0.0.0.0
Application Timestamp: 53dd642c
Fault Module Name: TestArraySort.exe
Fault Module Version: 0.0.0.0
Fault Module Timestamp: 53dd642c
Exception Code: c0000005
Exception Offset: 00011727
OS Version: 6.1.7601.2.1.0.256.4
Locale ID: 1033
Additional Information 1: 0a9e
Additional Information 2: 0a9e372d3b4ad19135b953a78882e789
Additional Information 3: 0a9e
Additional Information 4: 0a9e372d3b4ad19135b953a78882e789
【问题讨论】:
-
我不太懂 C++,但我认为在分配给
ptr时,您应该使用nullptr而不是NULL和0。 -
如果你使用 C++,你真的应该使用更多的 STL。也就是说,你不应该使用
new int[]使用vector<int>;你不应该使用qsort,你应该使用std::sort。我还没有查看你所有的代码,但看起来你正在访问越界内存,使用 C++ 构造会有所帮助。 -
在
operator=你需要做L = obj.L在使用它分配新内存之前 -
ROW(ROW &obj);应该是ROW(ROW const &obj); -
如果列表长度不同且一个是另一个的子集,则比较器返回
0
标签: c++ c pointers struct qsort