### [Problem] Char pointer

Dear C++ community

I came across some code I needed to give the exact output of ( but did not understand what the "foo" functon does - why multiply i by 11 and the mod by 8 -?

The code works and is supplemented by my lecturer:

*My understanding is that it is trying to sort the chars into different positions.

 ``12345678910111213141516171819202122`` `````` Put the code you need help with here. #include using namespace std; char foo(char* p, int i){ return p[(11*i)% 8]; } int main() { char* pRan = "lhaargpo"; cout<< pRan +3 << "!\n"; for(int i=0; i < 8 ; i++){ cout<< foo(pRan,i); } cout<<"!\n"; return 0; } ``````
Last edited on
Line 12: pRan is a pointer that points to the string literal "lhaargpo".
Line 13: Print out the string literal starting from after its 3rd character (skips the l, h, a).

The foo function is just doing some funky math to pick a particular character in a deterministic way.
for i = 0, it calculates (11*0)%8 == 0, so it returns p[0] which is l.
for i = 1, it calculates (11*1)%8 == 3, so it returns p[3], which is a.
etc.
Why multiply by 11 and then mod by 8? I don't see any real rhyme or reason to it, just looks like a contrived example.
The loop then prints each character returned from the function.

Also, to be conforming C++, each char* should be a const char* in your code, since you're pointing to a string literal.

"Sorting" implies some sort of well-agreed comparison between objects. I would say this code is, in a way, shuffling what it prints.
Last edited on
Thank you, I really appreciate your help.
Topic archived. No new replies allowed.