Presentation - Pointers Array of Pointers KB
Presentation - Pointers Array of Pointers KB
syntax :
pointervariablename=&variablename;
For Example :
#include<stdio.h>
void main()
{
int val=100;
printf("%u\n",&val);
printf("%d\n",val);
printf("%d\n",*(&val));
}
Why are Pointers Used ?
To return more than one value from a function
directly
#include<stdio.h>
#include<conio.h>
void main()
{
int n=10;
int *ptr;
ptr=&n;
printf("Value of n is %d",n);
printf("\nAddress of n is %x",&n);
printf("\nAddres of pointer is %x",ptr);
printf("\nvalue stored in pointer is %d",*ptr);
getch();
}
Example 2
#include<stdio.h>
#include<stdlib.h>
#define size 10
void main()
{
char name[size];
char *i;
printf("\n Enter your name ");
gets(name);
i=name;
printf("\n Now printing your name is :");
while(*i != '\0')
{
printf("%c",*i);
i++;
}
}
Explain how the variable can be accessed by pointer
#include<stdio.h>
#include<conio.h>
void main()
{
int r;
float a,*b;
clrscr();
printf("\n Enter the radius of the circle");
scanf("%d",&r);
a=3.14*r*r;
b=&a;
printf("\n The value of a=%f",a);
printf("\n The value of a=%u",&a);
printf("\n The value of b=%u",b);
printf("\n The value of a=%f",*b);
getch();
}
Pointer Arithmetic
Addition and subtraction are the only operations that can be
performed on pointers.
Then ptr_var has the value 1000 stored in it. Since integers
are 2 bytes long, after the expression “ptr_var++;” ptr_var will
have the value as 1002 and not 1001.
Pointer Increment process example
#include<stdio.h>
#include<conio.h>
void main()
{
int *ptr; //static memory allocation
clrscr();
ptr=(int *) malloc(sizeof(int));
*ptr=100;
printf("\n%u\n",ptr); //address of ptr
printf("\n%d\n",*ptr);
ptr++; // increment 2 bytes
*ptr=101;
printf("\n%d\n",*ptr);
free(ptr);
getch();
}
* It is the complement of
&. It returns the value contained
in the memory location pointed
to by the pointer variable’s value
Write a C program to find the length of the string Using Pointer
#include<stdio.h>
#include<string.h>
void main()
{
char *text[20],*pt;
int len;
pt=*text;
printf("Enter the string");
scanf("%s",*text);
while(*pt!='\0')
{
putchar(*pt++);
}
len=pt -*text;
printf("\nLength of the string is %d",len);
}
/*Add Two Numbers using pointers*/
#include<stdio.h>
void main()
{
int a,b,*c=&a,*d=&b;
printf(“Enter two numbers to be summed");
scanf("%d %d",&a,&b);
printf(“The sum of two numbers=%d",c + d);
getch();
}
Pointers With Arrays
The address of the data item is passed and thus the function
can freely access the contents of that address from within the
function
Mr.Kartik.74
8839724192