#include <iostream>
using namespace std;
(Not related to the title, but using namespace std
is bad practice that can lead to breakage when switching compilers, for example. Better write the std::
prefix when needed, such as std::cin >>
.
int main() {
int n;
cin>>n;
int *p = new int(sizeof(int)*n);
The above is allocating a single int object, whose value is sizeof(int)*n
, and p
points to that integer. You probably mean:
int *p = (int*)malloc(sizeof(int)*n); // bad style
... at the end:
free(p);
But using malloc
in C++ is a bad idea, unless you want to go closer to the operating system for educational purposes.
Slightly better is to use new
, which besides allocating the objects also calls their constructors (but nothing is constructed for basic types such as int
).
int *p = new int[n]; // so-so style
... at the end:
delete [] p;
The above is not the best practice because it requires manual memory management. Instead, it is recommended to use smart pointers or containers whenever possible:
std::vector<int> p(n);
// continue with the code, just like with the pointers
Or allocate the individual elements only when needed.
std::vector<int> p;
p.reserve(n); // this is a minor optimization in this case
// ...
if (int value; std::cin >> value)
// This is how to add elements:
p.push_back(value);
else
std::cin.clear();
This looks ok:
int q = n;
for(int i=0;i<n;i++)
{
cin>>*p;
p++;
}
But this is broken. When the loop starts, p
points after the last element. The following *p
dereferences a pointer which goes past the last element:
for(int j=0;j<n;j++)
{
cout<<*p<<" ";
p--;
}
Replacing the order of pointer decrement and dereference avoids the crash:
for(int j=0;j<n;j++)
{
p--;
std::cout << *p << " ";
}