Dubby
Dubby

Reputation: 1144

Pointers to struct and array in C

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
}
  1. In line 2 I'm accessing the array arr using the . (dot) operator and not the -> operator. Why does this work?
  2. When i rewrite line 2 as (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

Answers (3)

MobA11y
MobA11y

Reputation: 18870

  1. 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.

  2. 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

Eric Finn
Eric Finn

Reputation: 9005

  1. a[2] is not a pointer. The indexing operator ([]) dereferences the pointer (a[2] is equivalent to *(a+2)).
  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 malloced enough memory for one int, this will attempt to access unallocated memory. If you malloc(sizeof(int)*2), it should work.

Upvotes: 0

Quentin
Quentin

Reputation: 63124

  1. -> 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.

  2. The expression (a+2)->arr[1] is equivalent to *((a+2)->arr + 1).

  3. You allocated one single struct t for a[2].arr, then wrote in the second one. Oops.

Upvotes: 0

Related Questions