The following C program will print the shortest and longest string as t[0]
and t[n-1]
. However, when I run this code, it says there is a memory problem. What is wrong with my code?
The problem is the last two lines, with "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);
}