I was writing this code on codeblocks(only compiler I m having).When I encountered such a behaviour. plz Somebody suggest why is this happening with ct, am I missing something.
#include <stdio.h>
int main(int argc,char* argv[])
{
int lov[3][2]={0};
int ct=0;
char* art;
if(argc!=4)
return 1;
art=argv[1];
do
{
if(*art=='L' & *(art+1)=='o' & *(art+2)=='c')
{
printf("\n\n (art+3)=%s ,*(art+3)=%c ,*(art+5)=%c",(art+3),*(art+3),*(art+5) );
lov[ct][ct]=*(art+3)-48;
lov[ct][ct+1]=*(art+5)-48;
printf("\nct=%d,lov[x][x]=%d,lov[x][x+1]=%d ",ct,lov[ct][ct],lov[ct][ct+1]);
ct++;
}
art+=3;
}
while(*(art++));
getchar();
}
And on command prompt:-
>Resol.exe Loc2,5 Loc3,8 Loc5,4
Output:-
(art+3)=2,5 ,*(art+3)=2 ,*(art+5)=5
ct=0,lov[x][x]=2,lov[x][x+1]=5
(art+3)=3,8 ,*(art+3)=3 ,*(art+5)=8
ct=1,lov[x][x]=3,lov[x][x+1]=8
(art+3)=5,4 ,*(art+3)=5 ,*(art+5)=4
ct=5,lov[x][x]=4198582
,lov[x][x+1]=4
Why ct becomes 5????(last Line)
It would appear that
ctis being overwritten because you are accessinglovout of bounds. Your compiler is probably placingctandlovclose to each other on the stack which is whyctis being modified incorrectly.When
ctequals1you write tolov[ct][ct+1], which islov[1][2]. That is out of bounds. But the next time round you write tolov[2][2]andlov[2][3]and one of those will be the one that causes the modification toct.When you write
lov[ct][ct+1], that can only be valid forct == 0. All other values ofctresult in out-of-bounds access of the array.I would not be surprised if there are other such errors given the confusing nature of this code.