Home  >  Article  >  Backend Development  >  Why do indexes in C# arrays start from zero?

Why do indexes in C# arrays start from zero?

WBOY
WBOYforward
2023-09-15 14:57:031523browse

为什么 C# 数组中的索引从零开始?

An array is a pointer to an address in index memory. The index is the first element of the array. Here, an index is like an offset, a concept that even predates the origins of the C language.

Suppose your array elements start from 0Xff000 and have 5 elements, such as {35,23,67,88,90}. So the array in memory will look like this since int is stored using 4 bytes.

0Xff000 has 35
0Xff004 has 23
0Xff008 has 67
0Xff012 has 88
0Xff016 has 90

This means that when accessing the array, a zero offset will be index 0.

Let us further understand the concept of zero indexing in C# -

  • If the array is empty, then it has 0 elements and has a length of 0.
  • If an array has an element at index 0, its length is 1.
  • If an array has two elements 0 and 1 at index 1, then its length is 2.
  • If an array has three elements at index 0, 1 and 2, then its length is 3.

The following shows that arrays in C# start with index 0 -

/* begin from index 0 */
for ( i = 0; i < 10; i++ ) {
   num[ i ] = i + 10;
}

The above is the detailed content of Why do indexes in C# arrays start from zero?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete