I'm delving further into C++ and I've just come across pointers. In particular I'm running into trouble understanding the following program a little. Code is as follows:
I'll bold what I'm having trouble with.
// Ex4_09.cpp
//Calculating the primes
#include <iostream>
#include <iomanip>
using std::cout;
using std::endl;
using std::setw;
int main()
{
const int MAX(100);
long primes[MAX]= {2, 3, 5};
long trial(5);
int count (3);
bool found(false);
do
{
trial += 2;
found = false;
for(int i = 0; i < count; i++)
{
found = (trial % *(primes + i)) == 0; my question stems from this statement here. Is this equation taking trial and dividing it by every value in the array primes? or is it simply dividing and checking the remainder by the current value?
if(found)
break;
}
if (!found)
*(primes + count++) = trial
}while(count < MAX);
Just remember your order of operations, the stuff inside the brackets gets processed first. So in this case the variable 'primes' which is a pointer is being added to 'i' an integer. Because 'primes' is a pointer and therefore holds an address, adding 'i' to it modifys the address it references by the size of the base type * 'i'. Then the '*' operator dereferneces 'primes' and the equations completes as you would expect after that.
Man that's pretty fancy! So let me check my understanding:
*(primes + i) = *primes + *i and as a direct result, the compiler will check everything that is stored in that address? And from there it does the division?
Also, in the output statement,
cout << setw(10) << *(primes +i);
Why is 'i' included if it's already been saved to the primes array?
On that same note, I thought that you had to use the & operator to attain an address for a pointer. ie.
int number(0);
int *pnumber(&number); which is the same as
pnumber = &number;
Is this code possible simply by using the using the de-reference operator?
Sorry, for making you repeat yourself. I just enjoy understanding.
I think I may need to read through this chapter again. XD
Lol!!! I never noticed that! But no there are no distrubutive properties in C\C++ and you cannot dereference a variable that is not a pointer. The stuff in the brackets happens first, since 'i' has a value we add what that value currently is to 'primes' and THEN we dereference the pointer so that we can use the value at that address.