0

In the code, if we use an integer n to store strlen(str), the output by for loop becomes different than used here! Why is that happening?

void helper(char str[], int start){

int n=strlen(str)
if(str[start]=='\0'||str[start]=='\0')
    return;

helper(str,start+1);

if(str[start]=='p' && str[start+1]=='i'){
    for(int i=n;i>=start+2;i--){
        str[i+2]=str[i];
    }   
str[start]='3';
str[start+1]='.';
str[start+2]='1';
str[start+3]='4';
}

}

  • 1
    You need to show both versions of the code. You need to show how the output is different in both cases. You need to show how you are calling this function. It's very hard to answer a question when all you do is dump some code and ask what is wrong with it. – john Dec 21 '20 at 13:20
  • Probably you have undefined behaviour somewhere. If `n` equals `strlen(str)` then this code `for(int i=n;i>=start+2;i--){ str[i+2]=str[i];` is probably an error since `str[i+2]` would be an out of bounds array access. That **might** be the explaination for what you are seeing but without more context it's hard to say. – john Dec 21 '20 at 13:23
  • See also https://stackoverflow.com/questions/502856/whats-the-difference-between-size-t-and-int-in-c – Raedwald Dec 21 '20 at 13:24
  • 1
    possibly because the function `helper` changes the string? and therefore its length changes? – user253751 Dec 21 '20 at 13:26
  • `if(str[start]=='\0' || str[start]=='\0')` This is checking the same `str[start]` twice. – dxiv Dec 21 '20 at 23:29

1 Answers1

0

In order to complete your question, you should include your expected output and the one you got. Or the difference that you observe. Anyway, it seems that your code contains undefined behaviour / out of bond array access.

for(int i=n;i>=start+2;i--){
        str[i+2]=str[i];
}

If n is the size of the string, then at the first loop iteration, i+2 is greater than the string size.

Please complete your question to get more details.

aureliar
  • 1,476
  • 4
  • 16