0
我目前正在編寫一個程序,其目的是發送一個字符串數組到一個函數,該函數然後將做一個氣泡排序與數組,將數組中的較短的字符串移動到前面並將較長的琴絃移動到後面,以便預期的輸出應該是"shortest is cat, longest is elephant"
。C分割錯誤錯誤
它看起來很直觀,但我得到了一個分段錯誤,我查看了代碼的索引,但它似乎沒有超出界限,所以我不知道發生了什麼。這是我的示例代碼。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void fx(char* array[],int size);
int main()
{
char* t[]= {"horse","elephant","cat","rabbit"};
int n;
n = sizeof(t)/ sizeof(t[0]);
fx(t,n);
printf("shortest is %s, longest is %s\n",t[0],t[n-1]);
}
void fx(char* array[],int size)
{
int i;
int current,next,unsorted;
char* stringTemp;
do {
unsorted = 0;
for(i = 0; i < size-1; i++)
current = strlen(array[i]);
next = strlen(array[i+1]);
if(current > next)
{
stringTemp = array[i];
array[i] = array[i+1];
array[i+1] = stringTemp;
unsorted = 1;
}
}
while(unsorted);
}
也是一個關於字符串的快速問題。早些時候,當我盯着我存儲在char array[]
字符串,但我得到錯誤說最大聲明達到或類似的東西。是我做了什麼,或者你不能將字符串存儲在像這樣的char數組?
縮進與大括號不匹配。我想你想在'for()'子句後面有一個curly,在另外兩個關閉的子句之間有一個匹配的curly。 –
構建一個調試版本(將'-g'標誌添加到gcc)並在調試器中運行。調試器將停止發生崩潰的位置,並讓您檢查調用堆棧。如果崩潰不在你的代碼中,你可以走棧,直到最終到達你的代碼,然後你可以檢查變量的值。至少編輯你的問題以包含來自調試器的調用堆棧。 –