Pointer
to strings
char
str[6]=”HELLO”;
str[0]
str[1]
str[2]
str[3] str[4] str[5]
H |
E |
L |
L |
O |
\0 |
Addressà 1000 1001 1002 1003 1004 1005
str Ã
name of the string à base address of
the string à 1000
( str + 0 ) Ã ( 1000 + 0*1) Ã 1000 Ã &str[0]
( str + 1 ) Ã ( 1000 + 1*1) Ã 1001 Ã &str[1]
( str + 2 ) Ã ( 1000 + 2*1) Ã 1002 Ã &str[2]
( str + 3 ) Ã ( 1000 + 3*1) Ã 1003 Ã &str[3]
Here scale factor value is 1, since size
of char is only one byte.
*( str + 0 ) Ã *( 1000 + 0*1) Ã *(1000) Ã str[0] Ã
value
*( str + 1 ) Ã *( 1000 + 1*1) Ã *(1001) Ã str[1]Ã value
*( str + 2 ) Ã *( 1000 + 2*1) Ã *(1002)Ã str[2]Ã value
int a;
float b;
char str[10];
scanf(“%d %f %s”, &a, &b, str);
here for str & is not required, as string
name itself is an address of string.
Some programs based on this address of the string using the topic called pointer to strings:
#include<stdio.h>
int main()
{
char str[6]="hello";
int i;
for(i=0;*(str+i)!='\0';i++)
{
printf("%c",*(str+i));
}
getch();
}
#include<stdio.h>
int main()
{
char str[6]="hello";
int
i;
for(i=4;i>=0;i--)
{
printf("%c",*(str+i));
}
getch();
}
#include<stdio.h>
int main()
{
char str[6]="hello";
int i;
for(i=4;i>=0;i--)
{
printf("%c",*(&str[i]-i));
}
getch();
}
Declaring pointer to strings:
char str[6];
char * ptr;
ptr=str; -Ã here ptr contains base address of string.
#include<stdio.h>
int main()
{
charstr[6]="hello";
char * ptr;
for(ptr=str;*ptr!='\0';ptr++)
{
printf("%c",*ptr);
}
getch();
}
#include<stdio.h>
int main()
{
char str[6]="hello";
int
i;
char * ptr;
for(ptr=(str+4);ptr>=str;ptr--)
{
printf("%c",*ptr);
}
getch();
}
Finding length of the string using
pointer:
#include<stdio.h>
#include<conio.h>
int main()
{
char str[50];
char *ptr;
int c;
printf("\nEnter a string");
scanf("%s",str);
for(ptr=str,c=0;*ptr!='\0';ptr++)
{
c++;
}
printf("\nlength = %d",c);
getch();
}
Copying strings using pointers:
#include<stdio.h>
int main()
{
char str1[6]="hello";
char str2[6];
char *ptr1;
char *ptr2;
for(ptr1=str1,ptr2=str2;*ptr1!='\0'
;ptr1++,ptr2++)
{
*ptr2=*ptr1;
}
*ptr2='\0';
printf("\n
after copying str1=%s and str2=%s",str1,str2);
getch();
}
Finding length of the string using
pointer:
#include<stdio.h>
int main()
{
char str[50];
int
count;
char *ptr;
printf("\nEnter
a string");
scanf("%s",str);
for(ptr=str,count=0;*ptr!='\0'
;ptr++,count++);
printf("\n
lenght of the string = %d ",count);
getch();
}
To make the reverse of the string using pointer:
#include<stdio.h>
#include<conio.h>
int main()
{
char str[50];
char *ptr1,*ptr2;
char temp;
printf("\nEnter a string");
scanf("%s",str);
for(ptr2=str;*ptr2!='\0';ptr2++);
for(ptr1=str,ptr2=ptr2-1;ptr1<ptr2;ptr1++,ptr2--)
{
temp=*ptr1;
*ptr1=*ptr2;
*ptr2=temp;
}
printf("\n reverse %s ",str);
getch();
}
0 Comments