Hi!
I have written a function for passing a string into it and finding its length.
When I pass a string it prints a correct value.
But when I take two strings and passing them individual len(str1),len(str2) after scanning two strings it returns the wrong value.
In the first case I passed the each string immediately after scanning each of them.
In the second case I scanned the two strings first and passed them then,I got different
answers.Please help me.
First case input and output-
str1=vijay
str2=rajes
output-5,5
Second case input and output-
str1=vijay
str2=rajes
output-4,5
Ist case--

#include<stdio.h>
#include<conio.h>

main(){
       int len(char str[]);
       char str1[]="",str2[]="";
       printf("Enter a string= ");
       scanf("%s",str1);
       len(str1);
       scanf("%s",str2);
       len(str2);
       getch();
       }
int len(char str[]){
    int i=0;
    while(str[i]!='\0')
                       ++i;
    printf("%d",i);
}

2nd--

#include<stdio.h>
#include<conio.h>

main(){
       int len(char str[]);
       char str1[]="",str2[]="";
       printf("Enter a string= ");
       scanf("%s",str1);
       
       scanf("%s",str2);
       len(str1);
       len(str2);
       getch();
       }
int len(char str[]){
    int i=0;
    while(str[i]!='\0')
                       ++i;
    printf("%d",i);
}

Please help me change this program in order to get right thing,and mention the fault in the program.I guess it is becase of enter(\n) button.
Thanks in advance.

Which compiler you are using ? Are you not getting any error because you are not returning any int value from function "len" as define in declaration. It is giving correct result on VS2010.

You are overwriting your arrays, when you declare a variable char str1[]="" since you have not specified an array length but you have specified an array initialiser the compiler allocates exactly the right array size to fit the initialiser into it. In your case an array size of 1 or the equivalent of char str1[1]="" .

When you scanf your strings it copies the input string into the array and adds a zero terminator but that certainly goes outside the size of your allocated arrays.

In both cases that means the second scanf overwrites the input data of the first, in the second program this is evidenced by the length of the string being wrong.

Writing outside the bounds of an array is undefined behaviour, which is bad, and should be avoided.

Something like char str1[100]="",str2[100]=""; is a simplistic way to solve your problem (but don't type more than 99 characters).

sundip is also correct about failing to return a value from len.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.