[lug] c question, int passed by reference

Jeffrey Haemer jeffrey.haemer at gmail.com
Mon Oct 8 11:17:38 MDT 2007


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/19b4e2e3/attachment.html>


More information about the LUG mailing list