Pointer/Offset notation help

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
using namespace std;

int main()
{
	int b[] = { 2, 3, 4, 5, 6 };
	int *bPtr = b;

	cout << "Array subscripts are:\n";

	//here is array output
	for (int i = 0; i < 5; i++){
		cout << "b[" << i << "] = " << b[i] << '\n';

		cout << "The square is: " << b[i] * b[i] << endl;
	}
	cout << "\nPointer/offset notation where "
		<< "the pointer is the array name\n";

	for (int offset1 = 0; offset1 < 5; offset1++)
		cout << "*(b * " << offset1 << ") = " << *(b + offset1) << '\n';

	cout << "\nPointer subscript notation\n";

	for (int j = 0; j < 5; j++)
		cout << "bPtr[" << j << "] = " << bPtr[j] << '\n';

	cout << "\nPointer/offset notation\n";

	for (int offset2 = 0; offset2 < 5; offset2++)
		cout << "*(bPtr + " << offset2 << ") = "
		<< *(bPtr + offset2) << '\n';

}//end main 
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;
Last edited on
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>

using namespace 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;
}
Last edited on
but pointer offset is basically just doing something like this

cout << "number[i] : " << number[0 + i]; //The value stored in the i'th element

if you put that into a for loop and incremented i you could print each value just using pointer offset.

too square it you could do something like

 
cout << number[0 + i] * number [0 + i]; 
Last edited on
Topic archived. No new replies allowed.