Hello all I'm having trouble with this program. I'm suppose to print out an array of 5 numbers then square them. I did that. But then I'm suppose to do it again using pointer/offset notation. I have no idea how to square the pointers. Any help would be great thanks in advance.
You defined b as an array of ints right? Well you can also use b as a pointer to the first element of the array. Then dereferencing b gives you 2. Also, if you do something like *b = 4, you set b[0] to 4. You can also add an "offset" to be to change where you point at. So *(b+3) points to where b points at, but 3 elements later. That's equivalent to b[4] (remember index starts at 0, so *b and b[0] are the same) or 5.
What you absolutely cannot do though, is change where b points to. Do not try anything like this: int a = 5; b = &a;
Whenever I get confused about pointers and arrays I look at this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
usingnamespace std;
int main()
{
int number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
cout << "\n number : " << number; //address of first element
cout << "\n&number : " << &number; //address of first element
cout << "\n&number[0] : " << &number[0]; //address of first element
cout << "\n*number : " << *number; //The value stored in first element
cout << "\nnumber[0] : " << number[0]; //The value stored in first element
return 0;
}