Reputation: 3
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
Upvotes: 0
Views: 1980
Reputation: 206567
Problems I see:
Don't use gets
. It's a security hole. Use fgets
instead.
fgets(str[i], 40, stdin);
You are using incorrect size for word
. It needs to be of size 40
.
char word[40];
You are returning a pointer to the first element of word
from
longestStrInArr
. However, that memory is invalid once the function returns. Hence, your program has undefined behavior.
You can fix it by returning the index of the longest string in str
or by providing an input argument long enough to hold the longest string.
size_t longestStrInAr(char str[N][40], int size, int *length)
{
size_t index = 0
size_t i,j=0;
int len = 0;
*length = 0;
for(i=0;i<size;i++){
while(str[i][j]!='\0'){
len++;
j++;
}
if(*length<len){
*length = len;
index = i;
}
}
return index;
}
and then use it as:
size_t index = longestStrInAr(str, size, &length);
printf("longest: %s \nlength: %d\n", str[index], length);
Upvotes: 1
Reputation: 4881
You copy the string into local variable and then return pointer to it. But after returning, the variable is no longer valid. That is undefined behavior and "anything" can happen. In this case it seems some optimization or a debug helper turns it to null.
Instead just keep a pointer to the longest string in the str
array, don't copy anything and return that pointer. Alternatively, if you want to simplify it, return the i
index of the longest string.
Upvotes: 1