Reputation: 1144
Questions are based on the following code :
struct t
{
int * arr;
};
int main()
{
struct t *a = malloc(5*sizeof(struct t));
a[2].arr = malloc(sizeof(int));//line 1
a[2].arr[1] = 3; //line 2
}
arr
using the .
(dot) operator and not the ->
operator. Why does this work?(a+2)->arr[1] = 3
this works. But if I write it as (a+2)->(*(arr+1)) = 3
I get a message as expected identifier before '(' token
. Why is this happening?Upvotes: 2
Views: 112
Reputation: 18870
For line 1, the dot operator works in this case, because the array access dereferences the pointer for you. *(a+2) == a[2].
These two are equivalent in both value and type.
The "->" operator, expects an identifier after it, specifically the right argument must be a property of the type of the left argument. Read the messages carefully, it really is just complaining about your use of parentheses. (Example using the . operator instead: a[2].(arr)
is invalid, a[2].arr
is just dandy.)
Also, if we can extrapolate meaning from your code, despite its compilation errors, there is the potential for memory related run time issues as well.
Upvotes: 1
Reputation: 9005
a[2]
is not a pointer. The indexing operator ([]
) dereferences the pointer (a[2]
is equivalent to *(a+2)
).(*(arr+1))
is an expression. If you want to do it that way, you want to get the pointer (a+2)->(arr+1)
, then derefrence it: *((a+2)->arr+1)
. Of course, since you've only malloc
ed enough memory for one int
, this will attempt to access unallocated memory. If you malloc(sizeof(int)*2)
, it should work.Upvotes: 0
Reputation: 63124
->
dereferences a pointer and accesses its pointee. As you seem to know a[1]
is equivalent to *(a + 1)
, where the dereference already takes place.
The expression (a+2)->arr[1]
is equivalent to *((a+2)->arr + 1)
.
You allocated one single struct t
for a[2].arr
, then wrote in the second one. Oops.
Upvotes: 0