Cs1104 - Unit IV
Cs1104 - Unit IV
Pointer is a variable that stores/hold address of another variable of same data type/ t is also known
as locator or indicator that points to an address of a value. A pointer is a derived data type in C
float a;
int *ptr;
Dereferencing of Pointer
Once a pointer has been assigned the address of a variable. To access the value of variable, pointer
is dereferenced, using the indirection operator *.
int a,*p; a = 10;
p = &a;
printf("%d",*p); //this will print the value of a.
printf("%d",*&a); //this will also print the value of a.
printf("%u",&a); //this will print the address of a.
printf("%u",p); //this will also print the address of a.
printf("%u",&p); //this will also print the address of p.
KEY POINTS TO REMEMBER ABOUT POINTERS IN C:
• Normal variable stores the value whereas pointer variable stores the address of the variable.
• The content of the C pointer always be a whole number i.e. address.
• Always C pointer is initialized to null, i.e. int *p = null.
• The value of null pointer is 0.
• & symbol is used to get the address of the variable.
• symbol is used to get the value of the variable that the pointer is pointing to.
• If a pointer in C is assigned to NULL, it means it is pointing to nothing.
• Two pointers can be subtracted to know how many elements are available between these
two pointers.
• But, Pointer addition, multiplication, division are not allowed.
• The size of any pointer is 2 byte (for 16 bit compiler).
Example:
#include <stdio.h>
#include <conio.h>
void main(){
int number=50;
int *p;
clrscr();
p=&number;//stores the address of number variable
printf("Address of number variable is %x \n",&number);
printf("Address of p variable is %x \n",p);
printf("Value of p variable is %d \n",*p); getch();
}
Output
In the above program, the pointer *p will print all the values stored in the array one by one. We
can also use the Base address (a in above case) to act as pointer and print all the values.
Relation between Arrays and Pointers
Consider an array:
int arr[4];
element of an array. In the above example, arr and &arr[0] points to the address
Since, the addresses of both are the same, the values of arr and &arr[0] are also the same.
Enter 6 numbers:
Sum = 21
Pointers to functions/ Function Pointers
• A pointer to a function points to the address of the executable code of the function.
• We can use pointers to call functions and to pass functions as arguments to other functions.
• We cannot perform pointer arithmetic on pointers to functions.
• The type of a pointer to a function is based on both the return type and parameter types of
the function.
• A declaration of a pointer to a function must have the pointer name in parentheses.
• The function call operator () has a higher precedence than the dereference operator *.
Without them, the compiler interprets the statement as a function that returns a pointer to
a specified return type.
declare Pointer to function?
The effect of calling a function by its name or function pointer is the same. If we are using the
function pointer, we can omit the indirection operator as we did in the second case. Still, we use
the indirection operator as it makes it clear to the user that we are using a function pointer.
Example
#include <stdio.h>
int add(int,int);
int main()
{
int a,b;
int (*ip)(int,int);
int result;
printf("Enter the values of a and b : ");
scanf("%d %d",&a,&b);
ip=add;
result=(*ip)(a,b);
printf("Value after addition is : %d",result);
return 0;
}
int add(int a,int b)
{
int c=a+b;
return c;
}
Output
#include <stdio.h>
int main(void) {
// string variable
char str[6] = "Hello";
// pointer variable
char *ptr = str;
// print the string
while(*ptr != '\0') {
printf("%c", *ptr);
// move the ptr pointer to the next memory location
ptr++; }
return 0;
}
Using pointer to store string
We can achieve the same result by creating a character pointer that points at a string value stored
at some memory location.
In the following example we are using character pointer variable strPtr to store string value.
#include <stdio.h>
int main(void) {
#include <stdio.h>
// create a structure Subject using the struct keyword
struct Subject
{
// declare the member of the Course structure
char sub_name[30];
int sub_id;
char sub_duration[50];
char sub_type[50];
};
int main()
{
struct Subject sub; // declare the Subject variable
struct Subject *ptr; // create a pointer variable (*ptr)
ptr = ⊂ /* ptr variable pointing to the address of the structure variable sub */
return 0;
}
Output:
Output:
Second Employee:
Enter the name of the Employee (emp2): Maria
Enter the id of the Employee (emp2): 1109
Enter the age of the Employee (emp2): 23
Enter the gender of the Employee (emp2): Female
Enter the city of the Employee (emp2): Los Angeles
1. malloc()
2. calloc()
3. realloc()
4. free()
Before learning above functions, let's understand the difference between static memory allocation
and dynamic memory allocation.
Now let's have a quick look at the methods used for dynamic memory allocation.
malloc() function in C
The malloc() function allocates single block of requested memory.
• It doesn't initialize memory at execution time, so it has garbage value initially.
• It returns NULL if memory is not sufficient.
The syntax of malloc() function is given below:
ptr=(cast-type*)malloc(byte-size)
#include<stdio.h>
#include<stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
Output
Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30
calloc() function in C
The calloc() function allocates multiple block of requested memory.
• It initially initialize all bytes to zero.
• It returns NULL if memory is not sufficient.
Syntax of calloc()
ptr = (castType*)calloc(n, size);
Example:
ptr = (float*) calloc(25, sizeof(float));
Example program
#include<stdio.h>
#include<stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
Output
Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30
realloc() function in C
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc()
function. In short, it changes the memory size.
Let's see the syntax of realloc() function.
ptr=realloc(ptr, new-size)
Example program
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr, i , n1, n2;
printf("Enter size: ");
scanf("%d", &n1);
ptr = (int*) malloc(n1 * sizeof(int));
printf("Addresses of previously allocated memory:\n");
for(i = 0; i < n1; ++i)
printf("%pc\n",ptr + i);
/* Reallocating memory */
str = (char *) realloc(str, 25);
strcat(str, ".com");
printf("String = %s, Address = %u\n", str, str);
/* Deallocate allocated memory */
free(str);
return(0);
}