Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

question related to the index of arrays in c language

Tags:

c

windows

why arrays first index starts with 0

like image 790
user530647 Avatar asked Dec 04 '10 18:12

user530647


2 Answers

Because index actually means the offset from the pointer. The offset of the first element is 0.

Update upon comment Well, I'll try.

Let's consider an array of bytes with 10 elements:

byte array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

Consider the memory cells where this array is located (lets assume it starts from the address 0010h):

   0010  0011  0012  0013  0014  0015  0016  0017  0018  0019
  +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
  |  1  |  2  |  3  |  4  |  5  |  6  |  7  |  8  |  9  |  10 |
  +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+

Our variable array points to 0010h.

The offset of 1 (the first element) is 0 and its actual address is 0010 + 0 (where 0010 is the address of array and 0 is the offset).

The offset of 3 (the third element) is 2 because it is in the third cell, and the cell size is 1 (because we have byte array). the 3rd element's actual address is 0010 + 2.

Coming back to our programming language: array[0] means the content of the memory cell which has the 0010 address, array[1] means the content of the memory cell with the 0010 + 1 address (the second element) and so on. *array in C refers to the first element, *(array+1) - to the second.

like image 189
khachik Avatar answered Oct 05 '22 12:10

khachik


The same reason that mathematically-minded people call tomorrow "one day from now" rather than "two days from now".

like image 44
R.. GitHub STOP HELPING ICE Avatar answered Oct 05 '22 11:10

R.. GitHub STOP HELPING ICE