Hi,
It goes to infinite loop because you are using the for loop wrong.
when you have done s[30], you have allocated s[0] to s[29]. Now if you
try to write anything to s[30], then you will be actually writing to
another variable, and in this case you are writing to the variable p
and making it 0. Now because p became 0, the for loop starts all over
again.
To make it simpler, this is how the allocation of stack will look like
for the function change():
c[0], c[1], ......c[29], s[0], s[1],.........,s[29], p, min, i, coin.
Now say s[29] will be at an address 100, then p will be at an address
104(if you consider int size as 4 bytes). In the for loop, you are
checking for p<=30. So when p becomes 30, you enter the loop and make
s[30]=0. s[30] will be calculated as address 104, which is nothing but
the variable p. So you will be assigning p to 0. so the loop starts
over again.
so to correct this, either you make c[30] and s[30] to c[31] and
s[31], or change the for loop to
for (p=0; p<n; p++)
Regards,
Srinivas.
On 11/15/08, suraj_joshi22 <suraj_joshi22@...> wrote:
> --- In c4swimmers@yahoogroups.com, Mallik <hi_malli2k3@...> wrote:
>>
>> Hi All,
>>
>> Could you please help me out in analysing this issue:
>>
>> I really find strange behavior with the following code. If the
> statement b is present as below, the for loop is executing infinitely.
> But when statement b is replaced with statement a as
>> int c[31], s[31];. Then the for loop is exited after n iterations.
> Below is my gcc version where i executed the code. Please help me out
> in this regard.
>>
>> int c [30], s[30]; // statement b
>>
>> #include <stdio.h>
>> void change (int a[], int, int);
>> int main ()
>> {
>> int d[3];
>> d[0] = 1, d[1] = 10, d[2] = 25;
>> int n = 30, k = 3;
>> change (d, k, n);
>> return 1;
>> }
>>
>> void change (int d[], int k, int n)
>> {
>> int c [30], s[30]; // statement b
>> c[0] = 0;
>> int p;
>> int min, i, coin = 0;
>>
>> for (p=1; p<=n; p++)
>> {
>> c[p] = 0;
>> s[p] = 0;
>> printf ("\n test : %d \n", p);
>> }
>> }
>>
>> gcc (GCC) 4.1.2 (Gentoo 4.1.2 p1.0.2)
>> Copyright (C) 2006 Free Software Foundation, Inc.
>> This is free software; see the source for copying conditions. There
> is NO
>> warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR
> PURPOSE.
>>
>> --
>> Thanks & Regards,
>> Mallik
>>
>>
>>
>>
>>
>> Dude it did not get into an infinite loop....Compiled using dev c++
> ver 4.9.9.0
>
>
>
>