这个程序中的分段错误在哪里?

时间:2013-03-21 19:16:20

标签: segmentation-fault

所有这一切都试图将最短字符串的地址放在数组末尾的最长字符串的开头和地址,但我看不出它有什么问题。当我在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;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

数组是[0 .... n-1]

len1 = strlen(t[n+1]); /*lenght of last string*/

应该是

len1 = strlen(t[n-1]); /*lenght of last string*/

len0,len1和len必须是int,而不是char *,因为它们持有字符串的len