+ 2
Can someone please tell me, what is this problem and how can i solve this?I already googled it and cannot understand even a wor
#include<iostream> using namespace std; int main() { int* ptr = NULL; ptr = new int[5]; int* ptr2 = ptr; cout << "Enter value: "; for (int i = 0; i < 5; i++) cin >> *ptr++; for (int i = 0; i < 5; i++) { cout << "\nValue: " << *ptr2; cout << "\tAddress: " << ptr2++; } delete[] ptr; }
3 Respostas
+ 4
When you allocate dynamic memory somewhere in the system, the allocator keeps track of how much memory was allocated. This is how 'delete' knows how much memory to free. However, in your code you were altering the value of ptr, causing delete to incorrectly free memory beyond the blocks which has been allocated.
Instead of
cin >> *ptr++;
do
cin >> ptr[i];
or
cin >> *(ptr + i);
Both examples above do not alter ptr.
+ 2
a[i] is equivalent to *(a+i). As you can see, the pointer is dereferenced when using this notation, so the value stored is returned instead of the address. If you want the address, just do ptr+i
+ 1
Thank you so much
Cin>>ptr[i]
This works fine
But when it comes to cout
cout<<ptr[i] it should print address but it is also printing value, i have to use & sign with it
Can you plz tell me why it is like this?