[LCP]query regarding pointers in C

Sameer Oak sameer.oak at mahindrabt.com
Fri Apr 16 13:04:01 UTC 2004


Sowmya,

1. #include<stdio.h>
   main()
   {
     int a=555,*ptr=&a,b=*ptr;
     printf("%d %d %d",++a,--b,(*ptr)++);
}
for this the output is 557 554 555

2. #include<stdio.h>
    main()
   {
     int a=555,*ptr=&a,b=*ptr;
     printf("%d %d %d",++a,--b,*ptr++);
}
for this i got the output as 556 554 555

...
do concentrate on the issue how the arguments are passed to the functions.
the sequence is LIFO(it can vary compilter to compilter, however).

1st program:
in printf() function, the arguments to the control strings are passed in the
LIFO order too.
thus in the first snippet, (*ptr)++ is passed to third %d, --b to the
second, and ++a to the first.

now look at (*ptr)++.
this way the value in the address ptr is pointing to is incremented after
it's assigned to the third %d.
it's postfix, you see. thus, at this instance, the third %d gets 555 and
then a is incremented to 556.
as --b has a prefix decrement operator attached, b is decremented first and
then assigned to the second %d.
now, while assigning ++a(note, it's a prefix increment operator) to the
first %d, the latest value of a is
accessed, which is of course 556, and then assigned.
thus, here a becomes 557.

2nd program:
(*ptr)++ and *ptr++ are definitely not the same, hope you agree.
the former, first assigns the value at the address ptr is pointing and then
increments the same while the latter one
accesses the value at the address ptr is pointing and then increments ptr,
but not the value at the address where ptr is pointing.

also, (*ptr)++ and ++(*ptr) have a difference of postfix operation and
prefix operation.

hope, this'll clear you doubt.
-
sameer oak.


*********************************************************
Disclaimer:          

This message (including any attachments) contains 
confidential information intended for a specific 
individual and purpose, and is protected by law. 
If you are not the intended recipient, you should 
delete this message and are hereby notified that 
any disclosure, copying, or distribution of this
message, or the taking of any action based on it, 
is strictly prohibited.

*********************************************************
Visit us at http://www.mahindrabt.com




More information about the linuxCprogramming mailing list