int main()
{
int *p = newint[5];
int *start = p;
for (int i = 0; i < 5; i++)
{
std::cout << "Address of p: " << p << std::endl;
*p++ = i;
}
p = start;
for (int i = 0; i < 5; i++)
{
std::cout << "p[" << i << "]: " << p[i] << std::endl;
std::cout << "\tAddress: " << &p[i] << std::endl;
}
for (int i = 0; i < 5; i++)
{
*(p++) = pow(i, 2); //Accomplishes same thing.
}
std::cout << "-----------------------------------------------------" << std::endl;
p = start;
for (int i = 0; i < 5; i++)
{
std::cout << "p[" << i << "]: " << *p << std::endl;
std::cout << "\tAddress: " << p << std::endl;
*(p)++;
}
p = start;
for (int i = 0; i < 5; i++)
{
(*p)++; //Increment value p is pointing to
*p++; //Increment p it move along in memory
}
std::cout << "------------------------------------------------------" << std::endl;
p = start;
for (int i = 0; i < 5; i++)
{
std::cout << "p[" << i << "]: " << *p << std::endl;
std::cout << "\tAddress: " << p << std::endl;
*(p)++;
}
delete[] p;
}
Both *p++ and *(p++) do the same thing. The ++ both times here is applied to the pointer p not the integer that it is pointing to. Additionally, *(p)++ also does the same thing.
Isn't pointer arithmetic wonderful? XD
Edited to insert missing 'delete' and change confusing comment
I'm not convinced that *p++ is the same as *(p)++ and *(p++)... I remember in my earlier courses my teacher told us the difference but I can't seem to remember
Move that '++' to the other side and you'll see a difference.
The POSTFIX ++ increments the pointer after the operation (assignment, printing, etc). PREFIX will do it beforehand.
1 2 3
int a = 5;
int b = a++;
int c = ++a;
What will the values of b and c be? They certainly will not be the same.
That's fine. There's no need to take anything on trust. Try out some examples of your own, test them and see what the results are. That's the way to understand this stuff.
++ is at precedence level 2, * is at precedence level 5 3. So, the post-increment happens first and the result of the post increment is dereferenced.. or, if we parenthesized the expression according to precedence we get:
*(p++)
That looks familiar, doesn't it?
*(p)++
() is at precedence level 1, so it is evaluated first leaving us with:
You also shouldn't assume that instructors are 100% correct all the time. I am a teacher at a university (I teach 23 students this semester - not programming, though), and also a student at the same university.
I had an instructor once tell me that static objects would be created after main if they weren't needed yet. I didn't know that was wrong until someone on here told it was.
I've also told my student something incorrect before due to oversight. Reading too fast, making a small mistake. It happens. I quickly fixed the mistake once I realized that I made it.