### Pointers

I am new to C++ and am trying to do some example problems before my exam next week. Could anyone provide any insight on how to do this?

Write a program segment that uses the pointer xPtr and a for statement to assign the three odd integers in array number to array odd.

Can be done in 4 lines of code.

Started with:

 ``1234567`` `````` int *Ptr, number[5]={1,2,3,4,5}, odd [3]; for (int i=0; i<5; ++i) number [i] = i; ptrA = number;``````

thank you!!
 ``1234567`` ``````int number[5]={1,2,3,4,5}; int odd [3]; for ( int *p = number, *q = odd; p != number + 5; ++p ) { if ( *p % 2 != 0 ) *q++ = *p; }``````

Or in other words

 ``12`` ``````std::copy_if( std::begin( number ), std::end( number ), std::begin( odd ), []( int x ) { return ( x % 2 ); } );``````
Last edited on
First, http://www.cplusplus.com/forum/beginner/1/

Then, what code was already given in the homework, and what have you written so far? It is hard to tell from your code.
 ``12345678910111213`` ``````int number[5] = {1, 2, 3, 4, 5}; int odd[3]; //array of 3 odd numbers; int *xPtr = odd; //xPtr now points to the first element of odd for(int i = 0; i <= 5; i+=2) //Start i at 1, increment by 2 for odd numbers *xPtr++ = numbers[i]; //Dereference xPtr to access the value pointed to by it. //set it equal to numbers[i]. (i will point to the first, third, and fifth element. //post-increment offsets xPtr by one, so it points to the next location in odd. //output odd to see if we did it right: for(int i = 0; i < 3; ++i) std::cout << odd[i] << std::endl;`````` ```1 3 5```

Hope that clears stuff up.

EDIT:
beat by vlad

EDIT2: Line 4, i should start at 0 not 1.
Last edited on
that is really helpful, thank you.

However, when i run the program, it outputs the even integers. If i change the initial value of i to 0, it outputs odd integers... Do you have any idea why?
Last edited on
Oh, woops. I made a silly mistake. You're right, the initial value should be zero.
Arrays start at zero and count up. so number[0] would be 1, numbers[2] would be 3.
I edited my post to reflect that error.
Topic archived. No new replies allowed.