所有这一切都试图做的是将最短字符串的地址放在数组的开头,将最长字符串的地址放在数组的末尾,但我看不出它有什么问题。当我在 linux 上运行它时,出现“分段错误”
#include <stdio.h>
#include <string.h>
void fx(char* t[], int n);
int main(void) {
char*t[]= {"horse", "elephant", "cat", "rabbit"};
int n, i;
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* t[], int n) {
int i;
char* temp, len0, len1, len;
len0 = strlen(t[0]); /* lenght of first string*/
len1 = strlen(t[n+1]); /*lenght of last string*/
for(i=0; i<n; i++) {
len = strlen(t[i]); /*temporary lenght if ith string*/
if( len < len0 ) {
temp = t[0]; /* if shorter, swap places with first*/
t[0] = t[i];
t[i] = temp;
}
else if(len > len1) { /* if larger, swap places with last*/
temp = t[n-1];
t[n-1] = t[i];
t[i] = temp;
}
}
}