C Language : Pointer Fundamental

No comments
Pointer Fundamental

In the simplest term pointer is a nearly integer variable which stores a memmory address of a computer which may contain other variable or even another pointer.

If a variable contains address of another variable than it is said that first variable points to second. Pointer can also be represented as a refrence to another variable but there is very subtle diffrence in the two statements which is mostly dependent upon situation and enviorment.

Pointer is generally of size of integer on the machine but it may be of different type which indicates the type of variable the pointer is pointing to decides pointers properties and behaviour. Pointer of one type cannot be implicitly converted from one type to another but can be explicitly converted using type casting. In such a conversion a pointer always assumes that it is point to a object of its type but reality may differ and if used incorrectly may lead to disasters including permanent machine damage.

Also it is important to note that all operation perform on pointers are done through two operators '*' (Star) and '&' (Ampercent). '&' is a unary operator that returns a memmory address of a variable. '*' is complement of '&' and return value stored at a memmory location stored in a pointer. '*' can interpreted as statement "at address" while '&' can be interpreted as statement "address of".


Pointer Variable

Declaring a pointer variable is quite similar to declaring an normal variable all you have to do is to insert a star '*' operator before it.


General form of pointer declaration is -

type* name;

where type represent the type to which pointer thinks it is pointing to.

Pointers to machine defined as well as user-defined types can be made.

Multiple pointers of similar type can be declared in one statement but make sure you use * before every one otherwise they will become a variable of that type.

Pointer Assignment

This is a type of expression used to assign value of one pointer to another using assignment operator '=' . In this value of right hand side points to memmory address of variable stored in left hand side pointer. As a result both pointers point to same memmory location after this expression.

Pointer of similar type can be used in expression easily as shown below but for diffrent type pointers you need to type cast them as shown in next section.

//
#include ‹stdio.h›
int main ()
{
   char ch = a;
   char* p1, *p2;
   p1 = &ch;
   p2 = p1; // Pointer Assignement Taking Place 
   printf (" *p1 = %c And *p2 = %c", *p1,*p2); // Prints 'a' twice
   return 0;
}

No comments :

Post a Comment