String segmentation fault
I have written code to expand a string like "a2b3" in "aabbb" in same string.
Code:
#include<stdio.h>
#include<string.h>
int main()
{
char str[50],var;
int i=0,sh=0,len;
printf("Enter String to expand: ");
scanf("%s",str);
len=strlen(str);
while(str[i] != '\0')
{
var=str[i];
printf("var is:%c ",var);
sh=shift(&str[i]);
printf("shift no is:: %d and i is: %d ",sh,i);
while(i<i+sh)
{
str[i]=var;
i++;
}
//break;
}
printf("%s",str);
return 0;
}
int shift(char *st)
{
char ch=*(st+1);
char *temp=st;
int shiftno=ch-48,i,len;
printf("passed string is: %s no is %d \n",st,shiftno);
if(shiftno <= 2)
{
while(*(st+2-shiftno) != '\0')
{
*st=*(st+2-shiftno);
st++;
}
*st='\0';
printf("fun :%s",temp);
}
else{
len=strlen(st);
for(i=len;i>0;i--)
*(st+i+shiftno-2)=*(st+i);
}
return (shiftno);
}
The above program is showing segmentation error after taking input and getting hang somewhere in shift() function.But when i make comment while loop in main() then shift function is working fine.
Is anyone can explain me this problem?
plz...