To most intents and purposes you could use it (as it stands) to access the elements of the numbers array. Line 4 currently points to the start of the array.
As it stands it is pointless (no pun intended) - you can access the elements of numbers[] directly and it's currently just an alias for the start of the array.
However, you might want to point it at other arrays at other times, or iterate through numbers[] in some non-standard way. So if you have some other code that you aren't showing ... it might be useful.
#include <iostream>
usingnamespace std;
int main()
{
int numbers[100];
int other_numbers[100];
for ( int i = 0; i < 100; i++ ) { numbers[i] = i; other_numbers[i] = 10 * i; }
int* iPointer; // declare a pointer capable of pointing to an int
iPointer = numbers; // set it to point to the start of the numbers array
// iPointer = &numbers[0]; // this would do the same thing
for ( int i = 0; i < 10; i++ ) cout << iPointer[i] << ' '; // this will print the first few elements of numbers[]
cout << '\n';
for ( int i = 0; i < 10; i++ ) cout << *(iPointer + i) << ' '; // so will this
cout << '\n';
iPointer = other_numbers; // set it to point to the start of the other_numbers array
for ( int i = 0; i < 10; i++ ) cout << iPointer[i] << ' '; // this will print the first few elements of other_numbers[]
cout << '\n';
}
int myfunc( int* iPointer, int n );
int numbers[100];
int result = myfunc( numbers, 100 );
C/C++ does not copy arrays to functions when we call function with array as argument.
For one, the function would have to allocate memory from stack for whole array. Copying whole array is obviously costly too.
Therefore, function's parameter is a pointer that merely stores the address of the first element of the array. The function call essentially starts with:
Also a means of getting dynamic memory off the heap.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
usingnamespace std;
int main()
{
int *iPointer = newint[100]; // get some memory off the heap
for ( int i = 0; i < 100; i++ ) iPointer[i] = i; // set some array values
for ( int i = 0; i < 10; i++ ) cout << iPointer[i] << ' '; // print them out
cout << '\n';
delete [] iPointer; // don't forget!
}
For other uses, see run-time-typing, polymorphism etc.
It basically means that the address of the first position of the array is stored in the pointer or in other words you can say that the pointer is pointing to the array.
Here, if we increment the function iPointer++ it will move to the next position.