[英]No errors or warnings but my code output is an endless stream
I am writing a program to sort an array of string pointers using a bubble sort.我正在编写一个程序来使用冒泡排序对字符串指针数组进行排序。 My code so far doesn't have any errors or warnings, but when I run it the output keeps looping and looping.到目前为止,我的代码没有任何错误或警告,但是当我运行它时,输出不断循环和循环。
I think it may be a problem in my sorting but I'm not positive.我认为这可能是我的排序问题,但我并不积极。
here is my main:这是我的主要内容:
int main(int argc,char**argv)
{
int size =0;
//array of string pointers
char *wordPtr[] ={"Eric", "Andrew", "Sean", "Daniel"};
//size is the size of the string
size = (sizeof(wordPtr))/(sizeof(wordPtr[0]));
//call funtion to print list
printArray(size,wordPtr);
}
I have a function for printing the list:我有一个打印列表的功能:
void printArray(int size,char**wordPtr)
{
//call sortArray to sort the list
sortArray(size,wordPtr);
//print ordered list
printf("Ordered List:\n");
printf("--------------\n");
printf("%s\n",wordPtr[0]);
printf("%s\n",wordPtr[1]);
printf("%s\n",wordPtr[2]);
printf("%s\n",wordPtr[3]);
}
and my sort function which I suspect is the problem.我怀疑是我的排序功能有问题。 I'm also not sure if I'm sorting the strings correctly.我也不确定我是否正确地对字符串进行了排序。 I get the feeling I'm just missing something silly but I can't seem to see it.我觉得我只是错过了一些愚蠢的东西,但我似乎看不到它。
void sortArray(int size, char**wordPtr)
{
char * temp = NULL;
int x = 3;
int j;
int i;
//sort list
for (j=0;j<=x;j++)
{
for (i=0; i< size-1; i++)
{
if (wordPtr[i][0] > wordPtr[i+1][0])
{
temp = wordPtr[i];
wordPtr[i] = wordPtr[i+1];
wordPtr[i+1] = temp;
}
}
}
//pass ordered list back to printArray
printArray (size,wordPtr);
}
Anything helps!什么都有帮助!
you are calling printArray forever now.你现在永远在调用printArray。 here is what your code do这是您的代码所做的
main -> printArray -> sortArray ┐
^
└------------------┘
to solve this problem.来解决这个问题。 you just delete call printArray() in your sortArray method.您只需在 sortArray 方法中删除 call printArray() 即可。
//pass ordered list back to printArray
printArray (size,wordPtr);
this is wrong way to pass ordered list back to printArray this is just call printArray() method again.这是将有序列表传递回 printArray 的错误方法,这只是再次调用 printArray() 方法。
in this code you don't need to pass any return because you are using pointer.在这段代码中,您不需要传递任何返回值,因为您使用的是指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.