1

This is an assignment and a question for measuring basic knowledge on C. It is part of a course on Coursera.org. But, this is just to measure if you are able to do the course. This is just a copy-paste of the actual question. I did great on all other question, I just don't seem to get the following one :

Suppose you are compiling for a 32-bit platform and sizeof(int) == 4. Which one of the following is equivalent to c[b] if c is of type int* and b is of type int?

Possible answers:

-1 * b[c]
*(c+b)
none of the above
*c+b
c[b][0]

What I am asking is, what the right answer is from the above possibilities, and why? I mean what logic does one use to arrive at the result? What should I read to understand the procedure to get there ?

2 Answers2

1
*(c+b)

It is known as Pointer Arithmetic.

AkaSh
  • 486
  • 4
  • 16
1
*(c+b)

This is equivalent to c[b] .

According to C99 standard -

6.5.2.1 Array subscripting

Constraints

1.One of the expressions shall have type ''pointer to complete object type'', the other expression shall have integer type, and the result has type ''type''.

Semantics

2 A postfix expression followed by an expression in square brackets [] is a subscripted designation of an element of an array object. The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).

Community
  • 1
  • 1
ameyCU
  • 16,489
  • 2
  • 26
  • 41
  • Thanks a lot. I was just shown another question, whose answer clarified me. Did not know about this a[b] == *(a + b) . Thanks a lot. – themasterishome Oct 07 '15 at 13:42