Vadamadafaka Vadamadafaka - 2 months ago 8
C++ Question

Dynamically Allocating Arrays Depending on User Input in C++

im watching this tutorial on youtube https://www.youtube.com/watch?v=8XAQzcJvOHk Dynamically Allocating Arrays Depending on User Input in C++

this is his code

1 int main()
2 {
3 int *pointer = nullptr;
4
5 cout << "how many items u are gonna enter" << endl;
6 int input;
7 cin >> input;
8
9 pointer = new int[input];
10
11 int temp;
12
13 for (int counter = 0; counter < input; counter++) {
14 cout << "enter the item " << counter + 1 << endl;
15 cin >> temp;
16 *(pointer + counter) = temp;
17 }
18
19 cout << "the items you have entered are" << endl;
20 for (int counter = 0; counter < input; counter++) {
21 cout << counter + 1 << " item is " << *(pointer + counter) << endl;
22 }
23
24 delete[]pointer;
25
26 return 0;
27}


im stuck in line 16, i dont understand why is that, inside the (), the pointer variable and counter are added to each other

Answer

This part:

*(pointer + counter)

is just simple pointer arithmetic: we are adding counter (of type int) to the pointer address and then dereferencing it using *. It is the same as pointer[counter]. After that, we are savig value of temp into that particular (dereferenced) location in memory.

Comments