Pointer Vs Arrays:
Pointers ana Arrays are strongly related. In fact, pointer and Arrays are interchangeable in many cases. For Example: a pointer that points to the beginning of an array can access that array by using either pointer arithmetic or array-style indexing. Consider the Following program.
/* Pointer Vs Arrays: InfoBrother:*/
#include <iostream>
using namespace std;
const int MAX = 3;
main ()
{
int var[MAX] = {10, 100, 200};
int *ptr; //pointer to int.
// let us have array address in pointer.
ptr = var;
for (int i = 0; i < MAX; i++)
{
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;
cout << "Value of var[" << i << "] = ";
cout << *ptr << endl;
// point to the next location
ptr++;
}
return 0;
}
Array Vs Pointer
Address of var[0] = 0xb4fd60
Value of var[0] = 10
Address of var[1] = 0xb4fd64
Value of var[1] = 100
Address of var[2] = 0xb4fd68
Value of var[2] = 200
However, pointers and arrays are not completely interchangeable. For Example: Consider the following program:
#include <iostream>
using namespace std;
const int MAX = 3;
int main ()
{
int var[MAX] = {10, 100, 200};
for (int i = 0; i < MAX; i++)
{
*var = i; // This is a correct syntax
var++; // This is incorrect.
}
return 0;
}
It is perfectly acceptable to apply the pointer operator * to var but it is illegal to modify var value. The reason for this is that var is a constant that points to the beginning of an array and can not be used as value. because an array name generates a pointer constant, it can still be used in pointer-style expressions, as long as it is not modified. For example, the following is a valid statement that assigns var[2] the value 500.
*(var + 2) = 500;
Above statement is valid and will compile successfully because var is not changed.
Most of the time, pointer and array accesses can be treated as acting the same, the major exceptions being.
Example:
Let's have an simple example to clear the concept what we discussed above.
/* Pointer Vs Arrays: InfoBrother.*/
#include <iostream>
using namespace std;
main()
{
float arr[5]; //array
float *ptr; //pointer
cout << "Displaying address using arrays: " << endl;
for (int i = 0; i < 5; ++i)
{
cout << "&arr[" << i << "] = " << &arr[i] << endl;
}
// ptr = &arr[0]
ptr = arr;
cout<<"\nDisplaying address using pointers: "<< endl;
for (int i = 0; i < 5; ++i)
{
cout << "ptr + " << i << " = "<< ptr + i << endl;
}
return 0;
}
Pointer Vs Array
Displaying address using arrays:
&arr[0] = 0xb4fd50
&arr[1] = 0xb4fd54
&arr[2] = 0xb4fd58
&arr[3] = 0xb4fd5c
&arr[4] = 0xb4fd60
Displaying address using pointers:
ptr + 0 = 0xb4fd50
ptr + 1 = 0xb4fd54
ptr + 2 = 0xb4fd58
ptr + 3 = 0xb4fd5c
ptr + 4 = 0xb4fd60