[lug] c question, int passed by reference
Carl Wagner
carl.wagner at verbalworld.com
Mon Oct 8 10:41:54 MDT 2007
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
More information about the LUG
mailing list