Thread: problem with Pointers and array

  1. #1
    Registered User
    Join Date
    Jan 2011
    Posts
    2

    problem with Pointers and array (SOLVED)

    Hi,
    I'm trying to write a simple program to learn and use array and pointer. It copies values from a vector to an array and prints the value of the array. Here is the portion of the code that causes problem:

    Code:
        int *pArr = new int[vect.size()] ;
        int *pArrBegin = pArr ;
        for ( vector<int>::iterator itr = vect.begin() ; itr != vect.end() ; itr++ ) {
            int *pItr = pArr;
            *pItr =  * itr ;
            pItr++ ;
        }
    
        cout << "Print Array: " << endl ;
        for ( int *pArrItr = pArrBegin  , *pArrEnd = pArr + vect.size(); pArrItr != pArrEnd; pArrItr++ ){
            cout << * pArrItr << " " ;
        }
    Here is the output:
    Code:
     
     ./copyVectorToArray 
    1 2 3 4 
    Print vec: 
    1 2 3 4 
    Print Array: 
    4 0 0 0
    I just don't understand why when I increment pltr, pArr and pArrBegin is also incremented.
    Last edited by platoali; 01-07-2011 at 02:13 PM.

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Code:
    for ( vector<int>::iterator itr = vect.begin() ; itr != vect.end() ; itr++ ) {
        int *pItr = pArr;
        *pItr =  * itr ;
        pItr++ ;
    }
    Being local to the loop, it gets recreated each iteration of the loop and is always pointing to first slot in the allocated memory at the point of the assignment below what I've marked. Thus, the remaining slots never get filled with data.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Registered User
    Join Date
    Jan 2011
    Posts
    2

    problem with Pointers and array (SOLVED)

    Thank you very much. It works now.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM
  2. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  3. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  4. Passing pointers between functions
    By heygirls_uk in forum C Programming
    Replies: 5
    Last Post: 01-09-2004, 06:58 PM
  5. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM