2

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?
1
  • 1
    Hello out-of-bounds access ! Commented Jul 9, 2014 at 14:17

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

1 Comment

Please correct part 2 of your answer. "dereference it *((a+2)->arr+1)"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.