What is a pointer? Explain pointer arithmetic with example. Also explain use of malloc function in C programming with an example.
Pointer :
A pointer is a variable that points to or references a memory location in which data is stored. Each
memory cell in the computer has an address that can be used to access that location so a pointer
variable points to a memory location we can access and change the contents of this memory location
via the pointer.
Pointer declaration:
A pointer is a variable that contains the memory location of another variable. The syntax is as shown
below. You start by specifying the type of data stored in the location identified by the pointer. The
asterisk tells the compiler that you are creating a pointer variable. Finally you give the name of the
variable.
type * variable name
Example:
int *ptr;
float *string;
Pointer Arithmetic
Like other variables pointer variables can be used in expressions. For example if p1 and p2 are
properly declared and initialized pointers, then the following statements are valid.
y=*p1**p2;
sum=sum+*p1;
z= 5* – *p2/p1;
*p2= *p2 + 10;
C allows us to add integers to or subtract integers from pointers as well as to subtract one pointer
from the other. We can also use short hand operators with the pointers p1+=; sum+=*p2; etc., we can
also compare pointers by using relational operators the expressions such as p1 >p2 , p1==p2 and p1!
=p2 are allowed.
/*Program to illustrate the pointer expression and
pointer arithmetic*/
#include< stdio.h >
main(){
int ptr1,ptr2;
int a,b,x,y,z;
a=30;b=6;
ptr1=&a;
ptr2=&b;
x=*ptr1+ *ptr2 –6;
y=6*- *ptr1/ *ptr2 +30;
printf(“\nAddress of a +%u”,ptr1);
printf(“\nAddress of b %u”,ptr2);
printf(“\na=%d, b=%d”,a,b);
printf(“\nx=%d,y=%d”,x,y);
ptr1=ptr1 + 70;
ptr2= ptr2;
printf(“\na=%d, b=%d”,a,b);
}
Malloc Function
Description:
The function malloc() returns a pointer to a chunk of memory of size size, or NULL if there is an
error. The memory pointed to will be on the heap, not the stack, so make sure to free it when you are
done with it. It is basically used in Dynamic Memory Allocation.
Example:
typedef struct data_type {
int age;
char name[20];
} data;
data *person;
bob = (data*) malloc( sizeof(data) );
if( person != NULL ) {
person->age = 22;
strcpy( person->name, “Robert” );
printf( “%s is %d years old\n”, person->name, person->age );
}
free( person );