简体   繁体   中英

Bubble sort program C

Write a function that when invoked as bubble_string(s) causes the characters in the string s to be bubble-sorted. If s contains the string "xylophone", then the following statement should cause ehlnoopxy to be printed. The errors I get are: 10.4.c: In function main': 10.4.c:3: warning: data definition has no type or storage class 10.4.c: In function main': 10.4.c:8: error: syntax error before "char" 10.4.c: In function `bubble_string': 10.4.c:17: error: syntax error before ')' token 10.4.c:18: error: syntax error before ')' token

Any ideas on how to fix this?

updated

Code:

#include <stdio.h>
void swap (char*, char*);
bubble_string(char s[]);

int main(void)
{
    char *s= "xylophone";
    printf("%s", bubble_string(char *s));

    return 0;
}

bubble_string(char s[])
{
    char i, j, n;
    n  = strlen(s);
    for(i = 0; i < n - 1; ++i)
            for(j = n - 1; j > 0; --j)
                    if(s[j-1] > s[j])
                            swap(&s[j-1], &s[j]);
}

Among other problems, you declare that bubble_string does not return a value (by giving it return type void ), then you go on to use it in the printf statement as if it returned a value. (At least that's how it looked before your edit...the way you have it now, it will default to returning an int, but you use it as if it were a string, and you're not actually returning anything from bubble_string .)

Also, your for loop syntax is way off. The outer loop should probably be more like:

for(i=0; i < n-1; i++) {/* et cetera */}

Your bubble_string function needs to return a char*. Otherwise it is returning a void to printf, which is causing your error (because printf is expecting a char*).

如果您在printf()中使用了bubble_string()函数,则需要返回一个char *。

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