[lug] c question, int passed by reference

Lori Reed lorireed at lightning-rose.com
Mon Oct 8 11:28:00 MDT 2007


Zan Lynx wrote:
> On Mon, 2007-10-08 at 10:41 -0600, Carl Wagner wrote:
> [snip]
>> 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).
> [snip]
>> 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);
>>
>> }
> 
> Operator precedence.  It translates it as *(k++) when what you want is
> (*k)++.  Just add parenthesis.

Zan's correct.

To elaborate, *k++; is incrementing the pointer, not what's being 
pointed at. The fact you're also pointing at the contents of the pointer 
  is a null op.

Lori





More information about the LUG mailing list