user41580
user41580

Reputation: 23

C array indexing

I have a pretty simple question but it confuses me a bit

For example:

int a[] = {0,1,2,3,4,5,6,7,8,9};

I have a question asking what the value of: a + 3 is

Simple question,what I tried was just adding 3 spots so the array would start from 2 and onwards.

Upvotes: 0

Views: 700

Answers (4)

Hamza
Hamza

Reputation: 1583

if you want the value of "a" then the value will be its address as array acts as a pointer and points to the first element of the array i.e. a[0] so lets suppose the address of a is 0059FE8C then the address of a+3 will be 0059FE98.

As each integer is of 4 bytes so add 4 each for each 0059FE8C +4+4+4= 0059FE98.

Now if you will do *(a+3) for int a[] = {0,1,2,3,4,5,6,7,8,9} then this means a[3] which has value 3.

Upvotes: 1

AnT stands with Russia
AnT stands with Russia

Reputation: 320381

Value of a + 3 is a pointer value of type int * that points to memory location of a[3] - an array element that contains value 3 in your example. That is a direct answer to the question you asked. Is that what you wanted to hear?

P.S. It is not clear what you mean by "array would start from 2 and onwards". Where did that "2" come from?

Upvotes: 4

haccks
haccks

Reputation: 106002

If the starting address of your array a is 1000 then a+3 would give you 1000 + 3*4, ie, 1012 (assuming int is of 4 bytes). It is because array names are decayed to pointers to its first element.
Dereferencing a + 3, which is a pointer to fourth element of the array, would give 3 (fourth element of the array).

Upvotes: 0

Martin Dinov
Martin Dinov

Reputation: 8815

If you just referenced a, it is a pointer to the first element of the array, so a[0] - that is, a pointer of type int *. Adding to the array is in most cases equivalent to adding to such a pointer, so a+3 will refer to a[3] or the value 3 in your case.

Upvotes: 1

Related Questions