Thread: pointers

  1. #1
    ... arjunajay's Avatar
    Join Date
    May 2005
    Posts
    203

    pointers

    If I use a pointer to an element in an std::vector, during reallocation of memmory, will my pointer point to an invalid location?
    Code:
    std::vector<int> a(10, 0);
    int *ptr = &a[4];
    I have had no problems till now...
    Can some one tell me a way to counteract this problem???

  2. #2
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Whenever you change the contents of the vector your pointer could become invalid. If you never change the vectors contents after getting the pointer to an element you are safe.
    If the contents change you could use a vector of pointers.
    Kurt

  3. #3
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    If I use a pointer to an element in an std::vector, during reallocation of memmory, will my pointer point to an invalid location?
    Yes. Presumably exceeding the capacity() of the vector causes the internal memory management to use new to create a new block of memory for the elements, then all the elements are copied to the new block, and then the old block is deleted. So, pointers that point to the old block of memory are no longer valid because the memory was deleted.

    Can some one tell me a way to counteract this problem???
    Make sure the capacity is large enough to start, so you don't have to reallocate? Check out reserve().

  4. #4
    ... arjunajay's Avatar
    Join Date
    May 2005
    Posts
    203
    Thanks I'll try that...

  5. #5
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Instead of keeping a pointer to the memory, keep an index. The index will always be valid unless you erase enough elements to make the size smaller than the index (which would make the pointer unusable as well).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Using pointers to pointers
    By steve1_rm in forum C Programming
    Replies: 18
    Last Post: 05-29-2008, 05:59 AM
  2. function pointers
    By benhaldor in forum C Programming
    Replies: 4
    Last Post: 08-19-2007, 10:56 AM
  3. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM
  4. Staticly Bound Member Function Pointers
    By Polymorphic OOP in forum C++ Programming
    Replies: 29
    Last Post: 11-28-2002, 01:18 PM