Print int pointer value

I am working on this and I cannot get it to work correctly. I am returning the last value of a list of pointers, and I would like to print it, but it prints a very random number. I assume this is the memory address of the pointer, but when I play it out, my output still does the same.

My Pointerlist is a list of pointers, for example: list<int*> pointerList

For example, this is my method returning:

 int* end() { return (pointerList.back()); } 

This is what I call him.

 int* totry = ca.end(); cout << *totry; 

This prints the memory address, not the value. Does anyone have any ideas how to solve this?

Thanks in advance!

EDIT: This is what the int pointers indicate: I have a list of values ​​like [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] And I have a list of pointers that point to different parts of this list, for example:

 [0,4,8,12] 

I have code: int* end() { return (pointerList.back()); } int* end() { return (pointerList.back()); } in my header file, and the call in my .cpp file:

int * totry = ca.end (); cout <* Totry;


This is how I declare my pointer

  class ptrList { public: std::list<value_type> listOfValues; std::list<*int> pointerlist; 

I populate the list pointers inside the add function, and I do it like this:

 int lstsqrt = 4; for (int a = 1; a < lstsqrt; a++) { int endptr = a + (int)lstsqrt; pointerlist.push_back((&*listOfValues.begin() + endptr)); //( (lstsqrt - 1) + a) ); } 

And this is my end () method

 int* end() {return (pointerlist.back());} 

And that is then passed to my toTry variable.

+4
source share
1 answer

One problem will probably be this:

 pointerlist.push_back((&*listOfValues.begin() + endptr)); 

Your listOfValues is std::list , so its values ​​are not stored in a contiguous block of memory. So, you get an iterator for the first element with listOfValues.begin() , dereferencing the iterator with * , taking the address of this with & , to get int* , and then adding some value that indicates somewhere in memory that you don't know what it is.

Try to do this instead:

 pointerlist.push_back((&*(listOfValues.begin() + endptr))); 

where you add endptr to the iterator (to promote it in the list), then look up and take the address. In fact, you may need advance instead of + .

+6
source

Source: https://habr.com/ru/post/1395867/


All Articles