Reputation: 12397
How to get size of a list using pointer ? I have the following piece of code. I put few integers inside and later, tried to get the size of the list.
#include <iostream>
#include <list>
using namespace std;
int main ()
{
list<int>* t;
for (int i=1; i<10; ++i)
{
t->push_back(i*10);
}
cout<<"size:\t"<<t->size()<<endl;
return 0;
}
Upvotes: 0
Views: 776
Reputation: 385104
You need to initialise the pointer to actually point somewhere. That could be a dynamically-allocated list using new
(in which case you should be using a smart pointer of some description), or it could be some other object that already exists (in which case this is "point"less, isn't it?).
Better yet, don't use a pointer:
list<int> l;
for (int i = 1; i < 10; ++i)
l.push_back(i*10);
cout << "size:\t" << l.size() << endl;
Upvotes: 7
Reputation: 2274
You haven't allocated t
. Write list<int>* t = new list<int>;
or better unique_ptr<list<int>> t (new list<int>);
if you are in c++11 . But in this case allocating list on the stack will work better anyway.
Upvotes: 2