Pointers and Strings

The arrays are implicitly treated as pointers. And the strings are array of characters terminated by NULL character. Hence a pointer to char type can be used to read a string.
Example: Program to read a String using Pointer

#include<stdio.h>
#include<conio.h>
int main()
{ int i; char *str1, str2[50], *ptr; clrscr();
printf("\n\tEnter a String-1: ");
scanf("%s", str1);
printf("\n\tEnter a String-2: ");
scanf("%s", &str2);
ptr = str1;
printf("\n\tThe String is : %s",ptr);
ptr = str2;
printf("\n\tThe String is : %s",ptr);
getch(); return 0;
}

To hold the list of names we can use Two dimensional array of characters. Consider the below example.
char s[3][50] = { “EDUSAT”, “PROGRAM”, “BANGALORE” };
char *ptr; ptr = s;

Here
s[0] = Address of the 0th String
s[1] = Address of the 1st String
s[2] = Address of the 2nd String

Program to Read a List of Names
#include<stdio.h>
int main()
{
int i , n; char names[10][50]; clrscr();
printf("\n\tEnter the Number of Names: "); scanf("%d", &n);
printf("\n\tEnter %d Names", n);
for(i = 0; i < n; i++)
{
printf("\n\tEnter Name-%d: ", i+1);
scanf("%s", names[i]);
}
printf("\n\tThe %d Names are: ", n);
for(i = 0; i < n; i++) printf("\n\t\t\t%s",names[i]);
getch();
return 0;
}
Pointers and Strings Pointers and Strings Reviewed by Unknown on 04:50 Rating: 5

No comments:

Powered by Blogger.