&
can be applied to any memory object such as an array or a variable, not to any expression, constant, or register
variable.p = &c; //p stores address of c
//remember p is a pointer type variable
int *p; //pointer to an int, this says that value at *p is an int
*
(value at) is the unary dereferencing operator and is used to access the value stored at a memory location.*p = 0; //value at p = 0
&
and *
have higher precedence than arithmetic operators.
++*ip; //increments value at ip
(*ip)++; //increments value at ip, parentheses are required here
iq = ip; //both are pointer variables to the same type, hence contents are copied into iq
swap(&a, &b);
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
arr
is same as &arr[0]
.int a[10];
int *p = &a[0];
//then to reach the ith element we can do -
int x;
x = *(p + i);
//this all is same as doing -
x = p[i];
The assignment p = &a[0];
is the same as p = a
.
An arary name is not a variable so expressions like - arr = p
and arr++
are illegal.
func(int a[]) {...}
//can also be written as -
func(int *a) {...}
0
being an execption.int *p = 0; //valid
if(*p == 0) //valid
//we can also use NULL defined in <stdio.h>
int *p = NULL;
p < q; //this is true if p referes to an earlier element in an array, p and q must belong to the same array
void*
to the pointer of another type without a cast.char amessage[] = "now is the time"; /* an array */
char *pmessage = "now is the time"; /* a pointer */
int arr[10][10]; //no. of rows = 10, no. of coloumns = 10
int func(int arr[5][5]) { ... }
//or
int func(int arr[][5]) { ... }
//or
int func(int (*arr)[5]) { ... }
Only the first dimension can be skipped.
Pointer arrays have to be initialized before they can be used.
int a[10][20]; //Multi-dimensional array having 10 pointers, each pointing to array of 20 elements
int *b[10]; //pointer array of size 10, which can point anywhere
In an environment using C, we can pass command-line arguments to a program when it begins executing.
int argc
(argument count) and char *argv
(argument vector) are used for this.
By convention, with argv[0]
a program is called so argc
= 1.
By convention, argv[argc]
is a null pointer (=0).
echo hello, world
is represented as -
int (*func)(); //pointer to function returning an integer