Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you explain the purpose of array+5 in this program?

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.

like image 488
Samuel Giftson Avatar asked Jul 06 '19 23:07

Samuel Giftson


People also ask

What is the purpose of array in programming?

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.

What is array explain?

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.

What is array explain with example?

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];

What is array and explain types of array?

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.


1 Answers

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.

like image 114
Michael Chourdakis Avatar answered Oct 15 '22 15:10

Michael Chourdakis