(1) C\ C++. |
[1] Pointer Alises.
This small article shows how error might occurs when one pointer is used in terms of another pointer.
Mainly this article shows how reference to pointer can be used.
Content of pointer [i.e address] can be used in many ways, some on which are as follows :
[A] Content of one pointer, say 'a' can be copied into another pointer, say 'b' and
then pointer 'a' can be used in terms of pointer 'b'.
Example code:
[code]
void showdata(int *b)
{
printf("%d %d", b[0], b[1]);
}
void engine()
{
int *a = new int [2];
a[0] = 10;
a[1] = 20;
showdata(a);
}
Output:
10 20
[/code]
OK that's as simple as anything !!!
[B] Now, we can allocate memory in some entity and use that memory in some other entity.
Accessing the same actual pointer in between entities or functions.
Example code:
[code]
void engine(int *b)
{
b = new int[2];
b[0] = 10;
b[1] = 20;
}
void showdata()
{
int *a = NULL;
engine(a); //memory allocation\ initialization procedure
printf("%d %d", a[0], a[1]);
}
Output:
Runtime Error !!! [crash]
[/code]
Here output 10 20 might be expected, but it's not the case.
Note :
(i)while a is passed to engine() : a = b = NULL
(ii)in procedure engine() memory is allocated for pointer 'b' and not for pointer 'a'.
Therefore, when we return from engine(), 'a' is still equal to NULL and b was pointing to newly allocated memory.
Solution: Collect the pointer by reference.
Example code:
[code]
void engine(int* &b)
{
b = new int[2];
b[0] = 10;
b[1] = 20;
}
void showdata()
{
int *a = NULL;
engine(a); //memory allocation\ initialization procedure
printf("%d %d", a[0], a[1]);
}
Output:
10 20 //as intended[/code]
So, Pointer Alises can be used in two ways:
[1]Content based : accessing, the address that is pointed to by, the actual pointer through an alise.
[2]Address based : accessing, the address, of actual pointer through an alise.