[lug] c question, int passed by reference
siegfried
siegfried at heintze.com
Mon Oct 8 11:35:17 MDT 2007
Most binary operators evaluate from left to right. The exceptions are binary
operators that contain operator=.
Unary operators are weird because many have the same precedence level and
evaluate from right to left. It is very helpful to photocopy the operator
precedence page out of the famous K&R book (or the Stroustrup C++ book).
Siegfried
_____
From: lug-bounces at lug.boulder.co.us [mailto:lug-bounces at lug.boulder.co.us]
On Behalf Of Jeffrey Haemer
Sent: Monday, October 08, 2007 11:18 AM
To: Boulder (Colorado) Linux Users Group -- General Mailing List
Subject: Re: [lug] c question, int passed by reference
Carl,
Looks like your problem is that "*k++" means "*(k++)" . You want "(*k)++",
so you'll need to parenthesize it.
Alternatively, you could use ++*k
http://www.difranco.net/cop2220/op-prec.htm
On 10/8/07, Carl Wagner <carl.wagner at verbalworld.com > wrote:
I needed to create a small program that used an integer that was passed
by reference.
It passed fine but I could not increment the value of the integer, but I
could increment the pointer.
I finally resorted to doing an l = l+1; .
So why aren't the following functions, 'a' and 'b', the same? 'b' works
as expected, but 'a' increments the pointer
This is what I would expect if I did "k++" (without the asterisk).
Thanks,
Carl.
=================================
#include <stdio.h >
void a(int *k);
void b(int *l);
int
main(void)
{
int i,j,x;
i = 3;
a(&i);
j = 7;
b(&j);
}
void a(int *k)
{
printf("a1> k = %u\n", k);
printf("a1> *k = %u\n", *k);
*k++;
printf("a2> k = %u\n", k);
printf("a2> *k = %u\n\n", *k);
}
void b(int *l)
{
printf("b1> l = %u\n", l);
printf("b1> *l = %u\n", *l);
*l = *l +1;
printf("b2> l = %u\n", l);
printf("b2> *l = %u\n", *l);
}
================
Output
a1> k = 3220283020
a1> *k = 3
a2> k = 3220283024
a2> *k = 6550480
b1> l = 3220283016
b1> *l = 7
b2> l = 3220283016
b2> *l = 8
_______________________________________________
Web Page: http://lug.boulder.co.us
Mailing List: http://lists.lug.boulder.co.us/mailman/listinfo/lug
Join us on IRC: lug.boulder.co.us port=6667 channel=#colug
--
Jeffrey Haemer <jeffrey.haemer at gmail.com >
720-837-8908 [cell]
http://goyishekop.blogspot.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lug.boulder.co.us/pipermail/lug/attachments/20071008/e518471a/attachment.html>
More information about the LUG
mailing list