2012-08-04 68 views
-1

这里是我的代码:当我的数组输入是10001,那么它也进入另一个块输入[1] = 0,如果我已经把条件放在外层if if(input [j] = = 1)。任何人都可以告诉我为什么会发生这种情况?为什么它进入else时如果外部不是真的呢?

#include<stdio.h> 
int main() 
{ 
     unsigned int tcase=0,build=0,i=0,j=0,k=0,count=0; 
     unsigned int input[1000]; 
     scanf("%d",&tcase); 
     while(tcase--) 
     { 
       scanf("%d",&build); 
       for(i=0;i<build;i++) 
         scanf("%d",&input[i]); 

       for(j=0;j<build;j++) 
       { 
         if(input[j]==1) 
         { 
           if(j==0) 
           {  input[j+1]=1; 

             printf("fddf"); 
           } 
           else if(j==(build-1)) 
           { 
             input[j-1]=1; 

             printf("Gfgf"); 
           } 
           else 
           { 
             input[j+1]=1; 
             input[j-1]=1; 
             printf("awGfgf"); 
           } 
         } 
       } 
       for(k=0;k<build;k++) 

       { 
         if(input[k]==0) 
           ++count; 
       } 
       printf("%d\n",count); 
     } 
     return 0; 
} 
+0

可正常工作。它进入是因为在前面的迭代中(迭代j = 0),你将输入[1]的值改为1 – carlosdc 2012-08-04 17:57:43

回答

0

我会回答你的问题为基础,以埃里克·J的回答您的评论:

J.no u got it wrong by i/p 10001 i mean for input[0]=1,input[1]=0 and so on... so it only occupies 5 array spaces 

答案的要点是,你正在进入为1的第一个输入导致病情成功的第一次。稍后在每次迭代中,您不断更改输入数组的值,从而导致后续迭代进入条件。

至于你提到你的输入是

input[0] = 1 
input[1] = 0 
input[2] = 0 
input[3] = 0 
input[4] = 1 

现在,看到下面的代码的行为:

for(j=0;j< build;j++) 
{ 
    if(input[j]==1) /* First for input[0], this condition succeeds */ 
    { 
     if(j==0) 
     { 
      input[j+1]=1; /* This line changes input[1] to 1, so next time in the loop the condition if(input[j] == 1 will succeed */ 
      printf("fddf"); 
     } 
     else if(j==(build-1)) /* This condition will cause input[4] to be set to 1 and will cause if(input[j] == 1) to succeed for the last iteration of the loop */ 
     { 
      input[j-1]=1; 

      printf("Gfgf"); 
     } 
     else /** This condition will cause input[2] & input[3] to be set to 1 and will again cause if(input[j] == 1) to succeed in successive loop iterations **/ 
     { 
      input[j+1]=1; 
      input[j-1]=1; 
      printf("awGfgf"); 
     } 
    } 
    } 
1

这是因为您正在检查超过数组边界末尾的值,从而测试具有不确定值的内存。

你的数组定义为

unsigned int input[1000]; 

声明

if(input[j]==1) 

当j是10001个测试内存方式越过数组边界结束。记忆的价值是不确定的,实际上取决于许多因素。这个内存地址的值是1是非常不可能的(事实上,如果内存是真正随机初始化的,那么在2^32中机会是1)。

+0

J.没有你通过i/p 10001弄错了我的意思是输入[0] = 1,输入[ 1] = 0等等...所以它只占用5个数组空间 – shalini 2012-08-04 17:35:07

相关问题