I understand how most of it works, except for the second line in the main
function: int* end = array+5;
. How does that line work?
#inlcude <iostream>
int main()
{
int array[] = {10, 20, 29, 200, 2};
int* end = array+5;
for(int* it = array; it != end; ++it)
{
std::cout << *it << std::endl;
}
}
It is supposed to just print every element in the list.
In coding and programming, an array is a collection of items, or data, stored in contiguous memory locations, also known as database systems . The purpose of an array is to store multiple pieces of data of the same type together.
An array is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key. Depending on the language, array types may overlap (or be identified with) other data types that describe aggregates of values, such as lists and strings.
An array is a variable that can store multiple values. For example, if you want to store 100 integers, you can create an array for it. int data[100];
An Array is a Linear data structure which is a collection of data items having similar data types stored in contiguous memory locations. By knowing the address of the first item we can easily access all items/elements of an array. Arrays and its representation is given below.
it != end;
means that it reached the position [5], which is one after the last (4).
int* end = array + 5;
simply creates a variable pointing to that [5] position.
It works, but a much more clean and safe version is:
for(int i = 0 ; i < 5 ; i++)
{
std::cout << it[i] << std::endl;
}
Of course, you can replace the hardcoded 5 with sizeof(array)/sizeof(int)
, or, even better, use a std::array.
std::array arr<int,5> = {10, 20, 29, 200, 2};
for(int i = 0 ; i < arr.size() ; i++)
{
std::cout << arr[i] << std::endl;
}
or
std::array arr<int,5> = {10, 20, 29, 200, 2};
for(auto& it : arr)
{
std::cout << it << std::endl;
}
The latter forms are as fast as the plain raw array, but a lot safer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With