Thread: Counting evens via pointer

  1. #1
    Its hard... But im here swgh's Avatar
    Join Date
    Apr 2005
    Location
    England
    Posts
    1,688

    Counting evens via pointer

    Hi Guys

    I am trying one of exercises in my book and its asked me to create
    an array, pass it to a function and count the number of even numbers
    via a pointer.

    It compiles but my result is a garbage value? I dont get why as I
    have technically assign the value which is a pointer in main to zero.
    And I am sure I have dereferenced it correctly.

    Code:
    // function prototype
    void totalEven ( int[], const int, int* );
    
    // main function - driver //////////////////////////////////////////////////////
    //
    int main ( void )
    {
    	const int ARRAY_SIZE = 12;
    	int total = 0;
    
    	int data[ ARRAY_SIZE ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
    
    	totalEven ( data, ARRAY_SIZE, &total );
    	
    	std::cin.get(); // freeze console output window
       
            return 0; // retu#rn value from int main
    }
    
    // function to count total even numbers
    // in the passed array
    void totalEven ( int dat[], const int SIZE, int *pNum )
    {
    	for ( int k = 0; k < SIZE; k += 2 )
    	{
    		*( pNum )++;
    	}
    
    	std::cout << "Total even numbers: " << *pNum
    	       << std::endl;
    }
    Double Helix STL

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    I think you want (*pnum)++.

    Your current code is just moving away from total by doing pnum++ - the star to dereference it is just causing the compiler to read the location [which it probably optimizes out anyways].

    If you step through the compiler, you should see the pnum increment by 4 each time you find an even number, rather than the total value (*pnum) increment by 1.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Its hard... But im here swgh's Avatar
    Join Date
    Apr 2005
    Location
    England
    Posts
    1,688
    Thanks matsp. Its working now.
    Double Helix STL

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Quick Pointer Question
    By gwarf420 in forum C Programming
    Replies: 15
    Last Post: 06-01-2008, 03:47 PM
  2. Basic things I need to know
    By maxorator in forum C++ Programming
    Replies: 53
    Last Post: 10-15-2006, 04:39 PM
  3. Parameter passing with pointer to pointer
    By notsure in forum C++ Programming
    Replies: 15
    Last Post: 08-12-2006, 07:12 AM
  4. Direct3D problem
    By cboard_member in forum Game Programming
    Replies: 10
    Last Post: 04-09-2006, 03:36 AM
  5. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM