Question

How can I access a list in C++ by de-referencing the List pointer?

I get bad_alloc error when doing:

 List My_List = *ls;

ls is a List*. before in code, I had:

List* ls = & Temp_List;

I used the value of ls as an integer. I passed it through different functions. Now that I want to cast it back to List* and de-reference it, I get the error

Was it helpful?

Solution

If you allocate the list on stack, its address might get changed. But if you allocate it on heap, you won't lose the pointer to the list (new or malloc)

OTHER TIPS

Try this and see,

List *My_List = ls;

Actually, you did dereferenced your list pointer in this piece of code: *ls;

And then you created new list object on the stack in this code:List My_List and copied your list into this list in this piece of code: <newly created list> = <your list reference>

(heh. after applying dereference operator you get the reference. That's c++ for you)

and during this copy you probably get std::bad_alloc because copying lists involves memory allocations, and probably your original list is destroyed and hence your pointer to original list points at some random garbage, and based on this garbage program determines how much memory it should allocate for list copying. So ensure that your original list is still alive.

Or fix your code like this: List& My_List = *ls and get a crash somewhere later.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top