When calling the following function for the first time, the string it prints out is some weird ANSII characters. However, when I call on the function subsequently with the exact same variables, it gives the answer.
I understand that my code may not be the best way to do the required task. However I would like to understand why the function does not work on the first run but works on the subsequent runs.
Does this have anything to do with fflush ?
Code:
/* function call */
printf("\"%s\" is the midstr of \"%s\" from the position %d with length %d.\n" , midstr( str2 , str1 , start , len ) , str1 , start , len );
char *midstr( char *str2 , const char *str1 , int start , int len )
/* This function aims to copy a string of length len from str1 to str2 starting from start */
{
char string[80] = {0};
int count = 1 , reduce , j;
while ( *str1 != '\0' ){
count++;
str1++;
}
if ( start > count || (start + len) > count ) {
*str2 = NULL ;
return str2;
}
else {
reduce = count - start - len + 1;
str1 -= reduce;
string[len] = '\0';
while ( len > 0 ) {
printf("1%c\n" , *str1);
string[len - 1] = *str1 ;
len--;
str1--;
printf("%c\t" , string[len]);
}
}
str2 = string;
return str2;
}