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

时间:2022-04-30 08:53:28

All this is trying to do is putting the address of shortest string at the beginning and address of longest string at the end of array, but I can't see what is wrong with it. When I run it on linux I get '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 个解决方案

#1


0  

Array are [0....n-1]

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

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

should be

应该是

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

len0, len1 and len must be int, not char* since they hold the len of the strings

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

#1


0  

Array are [0....n-1]

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

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

should be

应该是

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

len0, len1 and len must be int, not char* since they hold the len of the strings

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