Pointers are often used with functions in two ways.
Passing address to a function
If we want to modify the passed value of variable in function we must pass the address of variables to the function.
Example:
void display(int *ptr);
int string_length(char *str);
void swap(int *p1,int *p2);
C program using pointer as function argument:
#include<stdio.h>
change(int *ptr1,int *ptr2);
main()
{
int a=10,b=20;
printf("\nBefore Change a=%d b=%d",a,b);
change(&a,&b); //passing address to function as argument
14) printf("\nAfter Change a=%d b=%d\n",a,b);
}
change(int *ptr1,int *ptr2)//ptr1 points to a and ptr2 points to b
{ *ptr1=200;
*ptr2=300;
}
Before Change a=10 b=20
After Change a=200 b=300
Functions and pointers
C Program passing an array to a function :
#include<stdio.h>
main()
{ int a[10],n,i;
void display(int *x, int n);
printf("\n How many numbers:");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n You entered \n");
display(a,n);
}
void display(int *ptr, int n)
{ int i;
for(i=0;i<n;i++)
printf("\t%d",*(ptr+i));
}
An array name is a pointer to the array. When we pass an array to a function, we are actually passing the base address of the array. This address can be stored in a pointer.
Function returning a pointer
Syntax : datatype * function_name(argument list);
Example: int *f1(int); char *f2 (int *,int*);
C program accepts the address of two integers variables and returns the address of the larger variable to main
#include<stdio.h>
void main()
{
int *larger(int*,int*); /* prototype*/
int n1,n2,*maxptr;
printf(“\nEnter two numbers:”);
scanf(“%d%d”,&n1,&n2);
maxptr=larger(&n1,&n2);
printf(“\n The larger number is %d:”,*maxptr);
}
int *larger(int *ptr1,int *ptr2)
{ if(*ptr1>*ptr2) return(ptr1);
else return(ptr2);
}
Also Read
- Static and Dynamic Memory Allocation
- Memory Leak and Dangling Pointer
- Memory Allocation for 2D Array
- Dynamic Memory Allocation
- Pointer Constant and Constant Pointer
- Pointer Declarations and their Meanings
- Initializing Pointer to Pointer
- Pointer to Pointer Multiple Indirection
- Relationship between Arrays and Pointers
- Pointer to Array
- Pointer Arithmetic
- Types of Pointers
- Illustrate Basic Pointer Use
- Using Pointer
- Intializing Pointer
- Declaring Pointer
- Application of Pointers
- Value Model VS Reference Model
- What is Pointer
Comments
Post a Comment
Please give us feedback through comments