Pointers and Strings

A string in C is an array of characters ending in the null character (written as ‘\0′), which specifies where the string terminates in memory. Like in one-dimensional arrays, a string can be accessed via a pointer to the first character in the string. The value of a string is the (constant) address of its first character. Thus, it is appropriate to say that a string is a constant pointer.

A string can be declared as a character array or a variable of type char *. The declarations can be done as shown below:

char country[ ] = “INDIA”; 
char *country = “INDIA”;

Each initialize a variable to the string “INDIA”. The second declaration creates a pointer variable country that points to the letter I in the string “INDIA” somewhere in memory.

Once the base address is obtained in the pointer variable country, *country would yield the value at this address, which gets printed through,

printf (“%s”, *country);

Here is a program that dynamically allocates memory to a character pointer using the library function malloc at run-time. An advantage of doing this way is that a fixed block of memory need not be reserved in advance, as is done when initializing a conventional character array.

Write a program to test whether the given string is a palindrome or not.

/* Program tests a string for a palindrome using pointer notation */
# include <stdio.h>
# include <conio.h>
# include <stdlib.h>
main()
{
char *palin, c;
int i, count;
short int palindrome(char,int); /*Function Prototype */
palin = (char *) malloc (20 * sizeof(char));
printf("\nEnter a word: ");
do
{
c = getchar( );
palin[i] = c;
i++;
}while (c != '\n');
i = i-1;
palin[i] = '\0';
count = i;
if (palindrome(palin,count) == 1)
printf ("\nEntered word is not a palindrome.");
else
printf ("\nEntered word is a palindrome");
}
short int palindrome(char *palin, int len)
{
short int i = 0, j = 0;
for(i=0 , j=len-1; i < len/2;i++,j--)
{
if (palin[i] == palin[j])
continue;
else
return(1);
}
return(0);
}

OUTPUT

Enter a word: malayalam
Entered word is a palindrome.
Enter a word: abcdba
Entered word is not a palindrome.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: