Introduction to Pointers
Pointer is new type of variable that holds the memory address of another variable.
If a variable p contains the address of another variable q, then p is said to point to q.
To declare a pointer variable: add a asterisk to the type you want to point to.
int *a;
Declares a variable a of type int *, which can be used to hold the address of (or a “pointer to”) an integer.
Two unary operators (“inverses”):
& operator - “address of” operator.
Returns the address of the variable it precedes.
int *p = &q;
* operator - “dereference” or “value of” operator.
Accesses the variable that the pointer points to.
Returns the value stored at the address that the pointer points to.
int r = *p;
Pointers: Example 1 void main() {
int x = 1, y = 2, z = 3;
int *ip;
ip = &x;
z = *ip;
printf("%d", z); // prints value to x
printf("%d", *ip); // prints value to x
}
In short: don’t confuse the * (dereference/value of) operator with the * in the declaration of a pointer variable (or with multiplication)!
int *p; // pointer declaration
*p = 100; // dereferencing
Another Example
int x = 1, y = 2;
int *ip;
char c;
char *cp;
ip = &x; /* ip now points to x */
printf( "%d\n", *ip ); /* prints 1 */
printf( "%d\n", *ip + 2 );
/* prints 3 */
y = *ip; /* y is now 1 */
*ip = 0; /* x is now 0 */
printf( "%d\n", x ); /* prints 0 */
//cp= &x; /* doesn’t work; types don’t match */
/*cp is not pointing anywhere */
*cp = ’z’;
cp = &c;
*cp = 'z';
printf( "%c\n", c ); /* prints z */
Pointer Arithmetic
Pointer addition: pointer plus int
if a pointer p points to an element of an array, then p + i is a pointer (of the same type) pointing to the ith element after the element pointed to by p.
Pointer subtraction: pointer minus pointer
If p and q point to elements of the same array, then q - p gives the number of elements between p and q.
Pointer comparison: pointer relation pointer
Permissible relations: ==, !=, <, <=, >, >=
If p and q point to elements of the same array, then p < q is true if p points to an earlier member of the array than q does. Note: CAN’T add two pointers, or perform any sort of multiplication, etc. A pointer is a physical memory location, represented by an integer, but you should never think of them as integers. (Try it!). Pointer arithmetic works at the level of “the next element in the array”, NOT at “the next physical memory address”.
Don’t Get Confused!Post by j.siam,
Ref-: Md Munirul Haque
excellent introduction to pointers
ReplyDelete