0

In a question I posted here: C++ - class issue

One of the replies, which was from @SanSS mentioned the following part of the reply:

Arrays in C are used through pointers...

How is this done? And, can you clarify this by an example if possible?

Thanks.

Community
  • 1
  • 1
Simplicity
  • 47,404
  • 98
  • 256
  • 385
  • 1
    This sounds like a more general "What are pointers" question. There are many answers worth reading here. If they do not cover your answer could you refine your question? – EnabrenTane Jan 23 '11 at 08:46
  • Arrays in C **are** pointers. There are many Q/As on SO and Google to help you out here... – aqua Jan 23 '11 at 08:56

1 Answers1

5

What is meant by that could be a couple of things:

1) the subscript operator is defined in terms of pointer arithmetic. C99 6.5.2.1/2 "Array subscripting" says:

The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))).

As an example, assume you have an array declated like so: char s[] = "012345";

All of the following evaluate to '4':

  • s[4]
  • *(s + 4)
  • 4[s] - this unusual construct might surprise you, but because of the way that subscripting is defined by the standard, this is equivalent to *(4 + s), which is the same as *(s + 4) and the same as s[4].

2) (closely related to the above) array names evaluate to pointers to the first element of the array in most expressions (being the operand to the sizeof operation being the main exception).

Michael Burr
  • 333,147
  • 50
  • 533
  • 760