简体   繁体   English

气泡排序程序C

[英]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. 编写一个函数,当以bubble_string(s)调用该函数时,将对字符串s中的字符进行冒泡排序。 If s contains the string "xylophone", then the following statement should cause ehlnoopxy to be printed. 如果s包含字符串“ xylophone”,则以下语句应导致ehlnoopxy被打印。 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 我得到的错误是:10.4.c:在main': 10.4.c:3: warning: data definition has no type or storage class 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 main': 10.4.c:3: warning: data definition has no type or storage class 10.4.c: In function :10.4.c:8:错误:语法错误在“字符”之前10.4.c:在函数“ bubble_string”中:10.4.c:17:错误:语法错误在“)”令牌之前10.4.c:18:错误:语法错误在“)”令牌之前

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. 除其他问题外,您声明bubble_string不返回值(通过给它返回类型void ),然后继续在printf语句中使用它,就好像它返回了值一样。 (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 .) (至少这就是您编辑之前的样子……现在的样子,它将默认返回一个int,但是您将其当作一个字符串来使用,实际上并没有从bubble_string返回任何bubble_string 。 )

Also, your for loop syntax is way off. 另外,您的for循环语法也很遥远。 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*. 您的bubble_string函数需要返回一个char *。 Otherwise it is returning a void to printf, which is causing your error (because printf is expecting a char*). 否则,它会向printf返回一个void,这会导致您的错误(因为printf需要一个char *)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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