Что такое array c
Перейти к содержимому

Что такое array c

  • автор:

C — Arrays

Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, . and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and . numbers[99] to represent individual variables. A specific element in an array is accessed by an index.

All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

Arrays in C

Declaring Arrays

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows −

type arrayName [ arraySize ];

This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type. For example, to declare a 10-element array called balance of type double, use this statement −

double balance[10];

Here balance is a variable array which is sufficient to hold up to 10 double numbers.

Initializing Arrays

You can initialize an array in C either one by one or using a single statement as follows −

double balance[5] = ;

The number of values between braces < >cannot be larger than the number of elements that we declare for the array between square brackets [ ].

If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write −

double balance[] = ;

You will create exactly the same array as you did in the previous example. Following is an example to assign a single element of the array −

balance[4] = 50.0;

The above statement assigns the 5 th element in the array with a value of 50.0. All arrays have 0 as the index of their first element which is also called the base index and the last index of an array will be total size of the array minus 1. Shown below is the pictorial representation of the array we discussed above −

Array Presentation

Accessing Array Elements

An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example −

double salary = balance[9];

The above statement will take the 10 th element from the array and assign the value to salary variable. The following example Shows how to use all the three above mentioned concepts viz. declaration, assignment, and accessing arrays −

#include int main () < int n[ 10 ]; /* n is an array of 10 integers */ int i,j; /* initialize elements of array n to 0 */ for ( i = 0; i < 10; i++ ) < n[ i ] = i + 100; /* set element at location i to i + 100 */ >/* output each array element's value */ for (j = 0; j < 10; j++ ) < printf("Element[%d] = %d\n", j, n[j] ); >return 0; >

When the above code is compiled and executed, it produces the following result −

Element[0] = 100 Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109

Arrays in Detail

Arrays are important to C and should need a lot more attention. The following important concepts related to array should be clear to a C programmer −

Sr.No. Concept & Description
1 Multi-dimensional arrays

C supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array.

You can pass to the function a pointer to an array by specifying the array’s name without an index.

C allows a function to return an array.

You can generate a pointer to the first element of an array by simply specifying the array name, without any index.

Kickstart Your Career

Get certified by completing the course

Что такое array c

Контейнер array из одноименного модуля представляет аналог массива. Он также имеет фиксированный размер.

Определение и инициализация

Для создания объекта array в угловых скобках после названия типа необходимо передать его тип и размер:

#include int main() < std::arraynumbers; // состоит из 5 чисел int >

В данном случае определен объект array из 5 чисел типа int. По умолчанию все элементы контейнера имеют неопределенные значения.

Чтобы инициализировать контейнер определенными значениями, можно использовать инициализатор — в фигурных скобках передать значения элементам контейнера:

std::array numbers <>; // состоит из 5 нулей

В данном случае пустой инициализатор инициализирует все элементы контейнера numbers нулями. Также можно указать конкретные значения для элементов:

std::array numbers ;

Фиксированный размер накладывает ограничение на инициализацию: количество передаваемых контейнеру элементов не должно превышать его размер. Можно передать меньше значений, которые будут переданы первым элементам контейнера, а остальные элементы получат значения по умолчанию (например, для целочисленных типов это число 0):

std::array numbers ; //

Однако если при инициализации мы предадим большее количество элементов, нежели размер контейнера, то мы столкнемся с ошибкой.

Стоит отметить, что начиная со стандарта C++17 при инициализации можно не указывать тип и количество элементов — компилятор выводит это автоматически исходя из списка инициализации:

std::array numbers ;

Однако в этом случае в списке инициализации в фигурных скобках должно быть как минимум одно значение.

Доступ к элементам

Для доступа к элементам контейнера array можно применять тот же синтаксис, что при работе с массивами — в квадратных скобках указывать индекс элемента, к которому идет обращение:

#include #include int main() < std::arraynumbers ; // получаем значение элемента int n = numbers[2]; std::cout #include #include #include int main() < const unsigned n = 5; std::arraypeople < "Tom", "Alice", "Kate", "Bob", "Sam" >; // обращение через индексы for(int i<>; i < n; i++) < std::cout std::cout >

Основные функции array

В контейнер array нельзя добавлять новые элементы, так же как и удалять уже имеющиеся. Основные функции типа array, которые мы можем использовать:

  • size() : возвращает размер контейнера
  • at(index) : возвращает элемент по индексу index
  • front() : возвращает первый элемент
  • back() : возвращает последний элемент
  • fill(n) : присваивает всем элементам контейнера значение n
#include #include #include int main() < std::arraypeople < "Tom", "Bob", "Sam" >; std::string second = people.at(1); // Bob std::string first = people.front(); // Tom std::string last = people.back(); // Sam std::cout // проверяем for (int i<>; i < people.size(); i++) < std::cout >

Несмотря на то, что объекты array похожи на обычные массивы, тип array более гибок. Например, мы не можем присваивать одному массиву напрямую значения второго массива. В то же время объекту array мы можем передавать данные другого объекта array:

std::array numbers1 < 1, 2, 3, 4, 5 >; std::array numbers2 = numbers1; // так можно сделать int nums1[] = < 1,2,3,4,5 >; //int nums2[] = nums1; // так нельзя следать

Также мы можем сравнивать два контейнера array:

std::array numbers1 < 1, 2, 3, 4, 5 >; std::array numbers2 < 1, 2, 3, 4, 5 >; std::cout numbers2) 

Два контейнера сравниваются поэлементно. Так, в примере выше очевидно, что контейнеры numbers1 и numbers2 равны. Тогда как сравнение массивов начиная со стандарта C++20 объявлено устаревшим.

Массивы

Массив - это совокупность переменных одного типа, к которым обращаются с помощью общего имени. Доступ к отдельному элементу массива может осуществляться с помощью индекса. В С все массивы состоят из соприкасающихся участков памяти. Наименьший адрес соответствует первому элементу. Наибольший адрес соответствует последнему элементу. Массивы могут иметь одну или несколько размерностей.

Массивы довольно тесно связаны с указателями. При обсуждении одного из этих понятий, как правило, ссылаются на другое. Данный раздел сайта рассказывает о массивах.

  • Одномерный массив
  • Создание указателя на массив
  • Передача одномерных массивов в функции
  • Двумерные массивы
  • Массивы строк
  • Многомерные массивы
  • Индексация с помощью указателей
  • Размещение массивов
  • Инициализация массива
  • Пример программы игры в крестики-нолики

C Arrays

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

To create an array, define the data type (like int ) and specify the name of the array followed by square brackets [].

To insert values to it, use a comma-separated list, inside curly braces:

int myNumbers[] = <25, 50, 75, 100>;

We have now created a variable that holds an array of four integers.

Access the Elements of an Array

To access an array element, refer to its index number.

Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

This statement accesses the value of the first element [0] in myNumbers :

Example

Change an Array Element

To change the value of a specific element, refer to the index number:

Example

myNumbers[0] = 33;

Example

// Now outputs 33 instead of 25

Loop Through an Array

You can loop through the array elements with the for loop.

The following example outputs all elements in the myNumbers array:

Example

Set Array Size

Another common way to create arrays, is to specify the size of the array, and add elements later:

Example

// Declare an array of four integers:
int myNumbers[4];

// Add elements
myNumbers[0] = 25;
myNumbers[1] = 50;
myNumbers[2] = 75;
myNumbers[3] = 100;

Using this method, you should know the size of the array, in order for the program to store enough memory.

You are not able to change the size of the array after creation.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *