Reputation: 13811
I'm a beginner in C and Let's say I have a code like this:
#include <stdio.h>
void test(char *t)
{
t++;
*t = 'e';
}
void main()
{
char a[] = "anto";
printf("%c\n",a[1]);
test(a);
printf("%c\n",a[1]);
}
This is the sample code, where I am figuring out how pointers work. According to me the statement:
t++;
in the above code will increment the address of array a
by 1
char
in the calling function test
. Fine, now as far I know the *
is used to retrieve the object value that the pointer points to.
But weirdly when I change the t++
to
*t++;
I'm getting the same output as before. I'm literally confused with this, the above statement
*t++;
should change the contents only know, according to the definition of *
operator.
But again this changes the address of t
. How come? Where I'm getting the concept wrong?
Thanks in advance
Upvotes: 0
Views: 1500
Reputation: 123458
Postfix ++
has higher precedence than unary *
, so *t++
is parsed as *(t++)
; you're dereferencing the result of the expression t++
; as a side effect, t
is advanced.
Unary *
and unary ++
have the same precedence, so if they appear in the same expression they would be evaluated left-to-right. The expression *++t
would be parsed as *(++t)
; you dereference the result of the expression ++t
, and as a side effect t
is advanced.
++*t
would be parsed as ++(*t)
; you're incrementing the result of the expression *t
.
Upvotes: 1
Reputation:
++
has greater precedence than *
so your expression evaluates to *(t++)
.
Upvotes: 2
Reputation: 7326
(*) operator is used to dereference a pointer.
t++;
as a statement returns the previous position of the pointer where as
*t++;
returns the value that the t pointer is pointed to before incrementing it.
The side effects of both statements are same, so you are getting the same output.
*t++;
statement does not change the value t is pointing to because ++ operator has greater precedence then * operator.
Upvotes: 4
Reputation: 81684
The expression *t++
is parsed as *(t++)
-- the ++
still applies to the pointer, not the contents. The value of t++
is the value of the pointer itself before the increment, while the value of *t++
is what the pointer points to before the increment.
Upvotes: 10