What's wrong with this program?

I've been trying to learn about pointers and vectors and had to create this program as an exercise in my book. Why doesn't it work (i was supposed to create a vector of ints and then copy the contents into a pointer to a new int[] but that was too challenging so i went with this (i.e. i was supposed to write *pia = new int[] instead of making an array), if you could help me on either question i'd appreciate it.


#include <iostream>
#include <vector>
using namespace std;

int main ()
{
vector<int> ivec(1);
vector<int>::iterator iter = ivec.begin();
while(cin >> *iter)
{
ivec.push_back(0);
++iter;
}
unsigned int asize = ivec.size();
int p[asize];
int *pp = &p[0];
iter = ivec.begin();
while(iter != ivec.end())
{
*pp = *iter;
pp++;
iter++;
}
unsigned int a = 0;
while(a != asize)
{
cout << *pp << endl;
pp++;
a++;
}
return 0;
}
You declared p but never used it, then declared *pp and defined it to point to the memory space of p but then later changed that. So I am confused on how you were attempting to do this. Try this:

1
2
3
4
for(int x=0;x<ivec.size();x++)
{
     p[x] = ivec[x];
}


This will populate your array from your vector. You don't even need the iterators here, save them for maps.
Topic archived. No new replies allowed.