[英]Segmentation fault in sorting algorithm
so when I run the following code in Xcode, it works, but gives segmentation fault when I run it in terminal and I'm not sure why. 因此,当我在Xcode中运行以下代码时,它可以工作,但在终端中运行时却出现分段错误,我不确定为什么。
void Word::arrangeWords(char **&words, int*& pages, int size)
{
char *lowest;
int track;
{
for (int i=0;i<size;i++)
{
lowest=new char[30];
strcpy(lowest, words[i]);;
for(int j=i+1;j<size;j++)
{
int compResult=strcmp(lowest, words[j]);
if (compResult>0)
{
strcpy(lowest, words[j]);
track=j;
}
}
std::swap(words[track],words[i]);
std::swap(pages[track],pages[i]);
delete [] lowest;
}
}
}
Thanks in advance 提前致谢
I can't figure out what's causing the segmentation fault but there is a bug in your code. 我不知道是什么造成了分段错误,但是您的代码中有一个错误。 You are not resetting the value of
track
after the calls to std::swap
. 在调用
std::swap
之后,您无需重置track
的值。 I suggest the following changes to the function. 我建议对功能进行以下更改。
void Word::arrangeWords(char **&words, int*& pages, int size)
{
for (int i=0;i<size;i++)
{
int track = i;
char lowest[30]; // If you know the size of the array to be 30,
// just create an array. Why use new char[30]?
strcpy(lowest, words[i]);;
for(int j=i+1;j<size;j++)
{
int compResult=strcmp(lowest, words[j]);
if (compResult>0)
{
strcpy(lowest, words[j]);
track=j;
}
}
if ( track > i )
{
std::swap(words[track],words[i]);
std::swap(pages[track],pages[i]);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.