我有以下代碼:功能使得陣列空
#include <stdio.h>
void insertion_sort(char[], int);
void swap(char*, char*);
int main() {
char s[] = "hello world";
puts(s);
insertion_sort(s, sizeof(s)/sizeof(char));
puts("done\n");
puts(s);
return 0;
}
void swap(char* a, char* b) {
char tmp = *a;
*a = *b;
*b = tmp;
}
void insertion_sort(char s[], int n)
{
int i,j;
/* counters */
for (i=1; i<n; i++) {
j=i;
while ((j>0) && (s[j] < s[j-1])) {
swap(&s[j],&s[j-1]);
j = j-1;
}
printf("%s\n", s);
}
}
的問題是,在insertion_sort()
函數調用後,s
成爲空 - puts(s)
什麼也不打印。
請指教。
嘗試單步執行調試器中的代碼 - 您不僅可以找到並修復您的錯誤,但是您將在此過程中學到很多知識。 – 2012-07-11 07:48:28
字符串的NUL終止符位於前面。這就是原因。 – nhahtdh 2012-07-11 07:49:07
@Paul我在Vim中編寫了這個應用程序,而不是帶有調試器的IDE。我希望它能在沒有調試的情況下工作。但感謝您的建議,我會嘗試在IDE中打開我的應用程序並對其進行調試。 – dhblah 2012-07-11 07:53:00