C编程指针char数组

use*_*356 2 c arrays string pointers

以下C程序将打印最短和最长的字符串as t[0]t[n-1].但是,当我运行此代码时,它表示存在内存问题.我的代码出了什么问题?

问题是最后两行,带有"strcpy".

#include <stdio.h>
#include <string.h>

void fx (char* t[], int n);

int main(void)
{
    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* t[], int n)
{
    char st[50], lt[50];
    strcpy(lt,t[0]);
    strcpy(st,t[0]);
    for (int i=0; i<n; i++)
    {
        if (strlen(t[i]) < strlen(st))
            strcpy(st,t[i]);
        if (strlen(t[i]) > strlen(lt))
            strcpy(lt,t[i]);
    }
    strcpy( t[0], st);
    strcpy( t[n-1], lt);
}
Run Code Online (Sandbox Code Playgroud)

Gri*_*han 7

两个strcpy()s,

strcpy( t[0], st);
strcpy( t[n-1], lt);
Run Code Online (Sandbox Code Playgroud)

错了!t[i]指向const字符串文字 - 不可修改,这会在运行时导致未定义的行为.