Tuesday, July 28, 2009

In "c " language why array starts from '0' i.e. base address starts from arr[0] why?

It is a convention in almost all programming languages and systems to start index at 0.








There are multiple reasons for this convention, mainly:


1. Memory addressing: arrays index resemble offsets, and starting from 1 would require either not using the first byte or an additional decrementing of the index to calculate the offset behind the scene.


2. If we start at zero, we utilize the entire integer space for addressing. Let's suppose that we have 1 byte memory for the index. If we start at 0, you can address 256 elements; but if you start at 1 for example, you will only address 255 elements only.

In "c " language why array starts from '0' i.e. base address starts from arr[0] why?
arr[0] means offset of 0 times the size of the array element from the start of the memory block where the array is stored. that is, it points to the first element, which is at the start of the memory block.





for example, if you have an array of int elements, each element is (usually) 4 bytes long. so the first element is at the first 4 bytes of the memory block, starting at offset 0 times 4 (==0), and continuing on offsets 1, 2, and 3. then arr[1] is on 1 times 4 (==4) continuing on 5, 6 and 7. and so on.





if the first element was arr[1], you would have to reduce 1 from the counter to get to the real place in memory. don't forget that C is tightly related to the hardware and uses memory addresses directly, unlike Java and other modern languages.
Reply:It's like that with every language.
Reply:For computers '0' is a starting point, as in: 0,1,2,3...and so on,and so to make keep things consistent i believe C developers felt it best to keep it closesly related to how computers deal with #s...Granted for beginners starting with an index of 1 is easier to grasp but in C where address referencing can be used then dealing with a starting address of memory will be an offset at "0"...the next element would be at that address + 1.

local florist

No comments:

Post a Comment