array passed as reference still doesnt modify its elements???

IndiraP's Avatar, Join Date: Nov 2012
Go4Expert Member
void fun(int *i);
void main( )
{
int gyan[] = { 10, 20, 30, 40, 50 };
int i, *ptr ;
ptr = gyan;
for ( i = 0 ; i <4 ; i++ )
{
fun(ptr++);
printf ( “\n%d”, *ptr ) ;
}
}
void fun(int *i)
{
*i = *i + 1;
}
Output is : 20 30 40 50
y not 11 21 31 41 since the array's reference is sent...but the modifications doesnt fall into the gyan[]..y???

Last edited by IndiraP; 19Nov2012 at 11:00..
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Have another look at the precise location of your post-increment operator. There should be a big clue in the fact that your output doesn't include 10.
0
IndiraP's Avatar, Join Date: Nov 2012
Go4Expert Member
ya ok sir..if i want to see the array again after the current for loop...again from 0 to 4 in another loop..y am i not getting the correct answerss??
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Hmm..ok..obviously that wasn't precise enough.

Explain to me EVERYTHING that this statement does: fun(ptr++);
0
IndiraP's Avatar, Join Date: Nov 2012
Go4Expert Member
ok sir..here goes..
given gyan[]={10,20,30,40,50};

func(ptr++) when called takes ptr[0] ie., 10 to its module does 10+1=11 n returns 11 to the main but the main now points to 20 n prints it...similarly
i=1=> 20 becomes 21 in func() n returns 21 to main() n 30 is printed by main()
i=2=>30 becomes 31 in func() n returns 31 to main() n 40 is printed by main()
i=3=>40 becomes 41 in func() n returns 41 to main() n 50 is printed by main()
i=4 conditions fails n comes out of the loop n the program here terminates..

since location of the element in the array is being sent, the modified must be present in that location of the array..??!!
now if i did
for(i=0;i<4;i++)
printf("%d",*ptr++);
i am getting some other values other than these..

i hope wat i understood is correct about func(ptr++) ..
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Hmm, you still can't see it. What is ptr pointing at after fun(ptr++) returns?

When exactly do you think that post-increment takes place? If you do this as a separate statement instead of in either line, which of these do you think the existing code is equvalent to:
Code:
ptr++;
fun(ptr);
printf ( “\n%d”, *ptr ) ; 

OR

fun(ptr);
ptr++;
printf ( “\n%d”, *ptr ) ; 

OR

fun(ptr);
printf ( “\n%d”, *ptr ) ; 
ptr++;
0
IndiraP's Avatar, Join Date: Nov 2012
Go4Expert Member
fun(ptr);
printf ( “\n%d”, *ptr ) ;
ptr++;

this one matches it...rite sir??
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Guess again.
0
IndiraP's Avatar, Join Date: Nov 2012
Go4Expert Member
fun(ptr);
ptr++;
printf ( “\n%d”, *ptr ) ;


ya..this one for sure... :| !!!!!
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
So have you figured out why the program doesn't do what you think?