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???
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.
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??
Hmm..ok..obviously that wasn't precise enough. Explain to me EVERYTHING that this statement does: fun(ptr++);
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++) ..
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++;
My favourite debugging technique is to get in there with a debugger, or failing that to sprinkle printf statements liberally across the code to display variables and why we are where we are, and find out what the program is *actually* doing. If you try debugging code based on what you *think* it's doing then you'll get nowhere, because you'll always think the code is doing what you were thinking when you wrote it - hence you not realising that ++ was in the wrong place.