array offset of pointer

Hi,

I'm learning C++ via tutorial videos as well as the book the tutor wrote.

The tutor illustrated the array offset in the programme which I transcribed as below. I understood most codes he typed but I'm confused about the array offset he was talking about.

For example:

1.The address of "a" for int a[] is 1000.
2.The the address for a[2] is (1000+4*2). (I'm able to understand this, because each int takes 4 bytes.)
3. But why does a[2] equal to *(a+2)? Or how do I understand this?

I think it should be *(a+4*2), though it is wrong.

Could anyone possibly use a easier way to help me with this as I am just a very beginner?

Many thanks!




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
35
#include<iostream>
using namespace std;
float average(int*, int);
int main(void)
{
	int a[100];
	float Average;
	int num=100;
	int i;
	for (i=0;i<100;i++)
		{
			a[i]=num;
			num++;
			cout<<a[i]<<endl;
		
		}
		Average=average(a, 100);
		cout<<"\n average:"<<Average<<endl;

   system("PAUSE");
   return EXIT_SUCCESS;
}
float average(int *p, int total)
{
	int sum=0;
	float b; 
	int i;
	for(i=0; i<total;i++)
		{
			sum=sum+p[i]; 
		}
	b=(float)sum/total;		
	 return b;	
}
Last edited on
I think you're a little bit confused about pointer operation.
When adding N to the pointer, it adds N * sizeof element to the address.
So that in your example, a + 2,
when a is an array of int, and its address is 1000, and the size of an int is 4
then a + 2 = 1000 + 2 * 4
If the pointer P points to the ith element of an array, then the expressions P+n, n+P, and P-n are pointers of the same type that point to the i+nth, i+nth, and i-nth element of the same array, respectively.

The result of pointer addition may also be a one-past-the-end pointer
(that is, pointer P such that the expression P-1 points to the last element of the array).

Any other situations (that is, attempts to generate a pointer that isn't pointing at an element of the same array or one past the end) invoke undefined behavior.
http://en.cppreference.com/w/cpp/language/operator_arithmetic


ie, if pointer p points to the 3rd element of an array, p+2 would point to its 5th element.
Hi liuyang and JLBorges,

Thank you both very much for your help. I've understood.

Have a great day!:)
Topic archived. No new replies allowed.