-2

Can someone tell me why this happens, what is wrong here:

I have to print a part of string where starting location and length of string to be printed is given in input.

PROBLEM: When i run it in devC++ everything runs fine and ok output. When i run it in IDEONE, the code produces no output [from the character array] unless i print the whole string using printf("%s\n",abc);

---> When i don't use printf("%s\n",abc); http://ideone.com/BMjCku

#include<stdio.h>
#include<ctype.h>

int main()
{
    long long int q;
    int length=0;
    scanf("%lld",&q);   
    while(q--)
    {
        int loc,cutlength=0,k=0,pos,plen=0;

        char abc[100001],save[100001],c;
        while(1)
        {
            scanf("%c",&c);
            if(c=='+' || c=='?')
                break;  
        }
        if (c=='+')
        {
            scanf("%d",&loc); pos=loc;
            cutlength=length-loc;
            for(int i=loc;i<=length-loc;i++)
                save[k++]=abc[i];
            scanf("%c",&c);
            while(!isalpha(c))
                scanf("%c",&c);
            while(1)
            {
                if(!isalpha(c))
                    break;
                abc[loc++]=c; length++; 
                scanf("%c",&c);
            }
            length+=pos+cutlength;
            for(int i=0;i<k;i++)
                abc[loc++]=save[i];
        }

        else if(c == '?')
        {
            if(&abc[0] == &abc[0]);
            scanf("%d%d",&loc,&plen);
            loc--;
            while(plen--)
                printf("%c",abc[loc++]);
            printf("\n");
            //printf("%s\n",abc);
        }
    }
    return 0;
}

---> When i use printf("%s\n",abc); http://ideone.com/Y6Sh5K

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
crazy_Fish
  • 78
  • 4

2 Answers2

0

The code in the c == '?' block uses the array abc when it is uninitialized.

It seems as if you think the data put in abc by the c == '+' block should remain when you go into the next loop iteration. However that is not true: the abc is local to the block opened by while(q--) {, so each loop iteration it is destroyed and recreated.

Possibly it appears to work on Dev-C++ because that does no checking, and re-uses the same piece of memory each time.

I guess you want to move some or all of the variable declarations at the start of the loop, to being before the loop.

M.M
  • 138,810
  • 21
  • 208
  • 365
0

You have abc declared in the while(q--) loop.

This means each iteration of the loop has its own uninitialized fresh copy of abc, not related to the previous iteration. Accessing any position of abc before initializing it is undefined behavior. That's what the if(c == '?') branch does.

Move the declaration out of the loop.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243