Reputation: 31
I've seen a very strange code snippet and i am not quite sure if i understood it right:
#include <stdio.h>
int main(char *argc, char **argv)
{
char a[50];
*(char *) (a + 2) = 'b'; // <== THE LINE WHICH CONFUSES ME
printf("value: %c\n", a[2]);
return 1;
}
Is it right that we go 2 buckets further cast the 'b' into a pointer to the b and then dereference it?
Upvotes: 1
Views: 1158
Reputation: 162289
*(char *) (a + 2) = 'b'; // <== THE LINE WHICH CONFUSES ME
This line literally means the very same as
a[2] = 'b'
The first cast (char*)
is redundant, since a is already of type char
. And indexing in fact translates to addition and dereferenciation, i.e.
a[n] === *(a + n)
A little known fact about C: You could write as well
n[a]
and get the same result.
Upvotes: 2
Reputation: 117761
No, you treat a
as a pointer, increment it by two, then cast it to (char*)
(useless cast, it already is char*
), dereference it and then store 'b'
into that.
It is exactly the same as this:
a[2] = 'b';
Upvotes: 1
Reputation: 145899
*(char *) (a + 2)
is equivalent to
a[2]
By definition, a[2]
is *(a + 2)
. The value of a + 2
is already of type char *
so a cast of a + 2
to char *
, as is (char *) (a + 2)
, is a no operation.
Upvotes: 3
Reputation: 5456
You aren't casting the 'b'
.
You cast (a+2)
to char*
(Which does nothing, since it's already char*
), deference it, and put there 'b'
.
And yes, it is right that we go 2 buckets further.
Upvotes: 1
Reputation: 75150
That's exactly equivalent of
*(a + 2) = 'b';
The cast is unnecessary.
All it does is add two to the array-which-decays-to-a-pointer a
, dereference the resulting pointer, and assign the character 'b'
to that memory location.
When a
is a pointer, the code a[x]
is exactly equivalent of *(a + x)
. So in your case, *(a + 2) = 'b'
is exactly the same as a[2] = 'b'
.
Upvotes: 6