I'm new to c programming, and i'm suppose to write a code to find the longest string and it's string length from an array of strings. This is my code so far.
#include <stdio.h>
#include <string.h>
#define N 20
char *longestStrInAr(char str[N][40], int size, int *length);
int main()
{
int i, size, length;
char str[N][40], first[40], last[40], *p;
char dummychar;
printf("Enter array size: \n");
scanf("%d", &size);
scanf("%c", &dummychar);
for (i=0; i<size; i++) {
printf("Enter string %d: \n", i+1);
gets(str[i]);
}
p = longestStrInAr(str, size, &length);
printf("longest: %s \nlength: %d\n", p, length);
return 0;
}
char *longestStrInAr(char str[N][40], int size, int *length)
{
int i,j=0;
int len = 0;
*length = 0;
char word[N];
for(i=0;i<size;i++){
while(str[i][j]!='\0'){
len++;
j++;
}
if(*length<len){
*length = len;
strcpy(word,str[i]);
}
}
return word;
}
The main{} is a given function, and the code under *longestStrInAr is the one im suppose to write. However, my current code is only able to give me the longest string length, and prints out (null) instead of the longest string. my output