+ 1

How to change the variable in a speceific place in an array stored in the heap? (C++)

Does anybody know how to change the value of an item of an array when the array is in the heap, y have tried with: pointer = new int[2]; *pointer [0] = 0; *pointer [1] = 1; cout << *pointer[0] << " and " << *pointer [1] << endl; delete []pointer; according to code blocks there are errors in the 2, 3 and 4 lines. obviously I have the main declaration, the include <iostream>, the using namespace std, the return 0 and everything. please help!!! [Closed]

13th Jul 2017, 10:27 PM
Fernando Rodriguez
Fernando Rodriguez - avatar
3 ответов
+ 2
p[0] is the same as *p p[1] is the same as *(p+1) *p[0] is the same as **p So don't do that here :) int* p = new int[2]; p[0] = 7; p[1] = 4; std::cout << p[0] << " " << p[1] << std::endl; delete[] p;
13th Jul 2017, 10:52 PM
Dennis
Dennis - avatar
+ 1
Try changing it to: *(pointer +1) and *pointer where you wrote *pointer[1] and *pointer[0] ...Though it's not necessary, you have [] for this.
13th Jul 2017, 10:58 PM
Jamie
Jamie - avatar
0
Thanks Jamie, but the code provided by Dennis worked (by the way, thanks Dennis)
14th Jul 2017, 1:00 AM
Fernando Rodriguez
Fernando Rodriguez - avatar