1

I am on youtube looking over tutorials. One had a block of code using the list library as such:

int arr1[5]{ 1,2,3,4,5 };
list<int> list1;
list1.insert(list1.begin(), arr1, arr1 + 5);

My question is, how can one use an array like this? Last I checked, arr1 is an array not a pointer that you use to loop through elements. How does the insert function work?

edo101
  • 629
  • 6
  • 17

2 Answers2

2

When an array is used by name, it's name references to first element of the array. For an array arr whenever you say arr[x], [] is defined in terms of pointers. It means start at a pointer referencing arr and move x steps ahead. A size of each step is the sizeof datatype your array is made up of. Thus,arr[x] can also be written as *(arr + x), dereferencing the pointer after x steps.

Now speaking of your list insertion, it means copy all the elements between pointers arr and arr + 5 to the list.

Bugman
  • 191
  • 6
0

arr1 can be used as a pointer to the beginning of the array, because it gets converted automatically.

Alejandro De Cicco
  • 1,216
  • 3
  • 17