[英]Bubble sort program C
編寫一個函數,當以bubble_string(s)調用該函數時,將對字符串s中的字符進行冒泡排序。 如果s包含字符串“ xylophone”,則以下語句應導致ehlnoopxy被打印。 我得到的錯誤是: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:錯誤:語法錯誤在“)”令牌之前
有想法該怎么解決這個嗎?
碼:
#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]);
}
除其他問題外,您聲明bubble_string
不返回值(通過給它返回類型void
),然后繼續在printf
語句中使用它,就好像它返回了值一樣。 (至少這就是您編輯之前的樣子……現在的樣子,它將默認返回一個int,但是您將其當作一個字符串來使用,實際上並沒有從bubble_string
返回任何bubble_string
。 )
另外,您的for
循環語法也很遙遠。 外循環應該更像是:
for(i=0; i < n-1; i++) {/* et cetera */}
您的bubble_string函數需要返回一個char *。 否則,它會向printf返回一個void,這會導致您的錯誤(因為printf需要一個char *)。
如果您在printf()中使用了bubble_string()函數,則需要返回一個char *。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.