简体   繁体   中英

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. here is what your code do

 main -> printArray -> sortArray ┐
              ^
              └------------------┘

to solve this problem. you just delete call printArray() in your sortArray method.

    //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.

in this code you don't need to pass any return because you are using pointer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM