• C Programming Video Tutorials

Character Pointers and Functions in C



What is a Character Pointer in C?

A character pointer stores the address of a character type or address of the first character of a character array (string). Character pointers are very useful when you are working to manipulate the strings.

There is no string data type in C. An array of "char" type is considered as a string. Hence, a pointer of a char type array represents a string. This char pointer can then be passed as an argument to a function for processing the string.

Declaring a Character Pointer

A character pointer points to a character or a character array. Thus, to declare a character pointer, use the following syntax:

char *pointer_name;

Initializing a Character Pointer

After declaring a character pointer, you need to initialize it with the address of a character variable. If there is a character array, you can simply initialize the character pointer by providing the name of the character array or the address of the first elements of it.

Character Pointer of Character

The following is the syntax to initialize a character pointer of a character type:

char *pointer_name = &char_variable;

Character Pointer of Character Array

The following is the syntax to initialize a character pointer of a character array (string):

char *pointer_name = char_array;
/*or*/
char *pointer_name = &char_array[0];

Character Pointer Example

In the following example, we have two variables character and character array. We are taking two pointer variables to store the addresses of the character and character array, and then printing the values of the variables using the character pointers.

#include <stdio.h>

int main() {
  // Declare two variables
  char x = 'P';
  char arr[] = "TutorialsPoint";

  // Declaring character pointers
  char *ptr_x = &x;
  char *ptr_arr = arr;

  // Printing values
  printf("Value of x : %c\n", *ptr_x);
  printf("Value of arr: %s\n", ptr_arr);
  
  return 0;
}

Output

Run the code and check its output −

Value of x : P
Value of arr: TutorialsPoint

Understanding Character Pointer

A string is declared as an array as follows −

char arr[] = "Hello";

The string is a NULL terminated array of characters. The last element in the above array is a NULL character (\0).

Declare a pointer of char type and assign it the address of the character at the 0th position −

char *ptr = &arr[0];

Remember that the name of the array itself is the address of 0th element.

char *ptr = arr;

A string may be declared using a pointer instead of an array variable (no square brackets).

char *ptr = "Hello";

This causes the string to be stored in the memory, and its address stored in ptr. We can traverse the string by incrementing the ptr.

while(*ptr != '\0'){
   printf("%c", *ptr);
   ptr++;
}

Accessing Character Array

If you print a character array using the %s format specifier, you can do it by using the name of the character pointer. But if you want to access each character of the character array, you have to use an asterisk (*) before the character pointer name and then increment it.

Example

Here is the full program code −

#include <stdio.h>

int main(){

   char arr[] = "Character Pointers and Functions in C";
   char *ptr = arr;

   while(*ptr != '\0'){
      printf("%c", *ptr);
      ptr++;
   }
}

Output

Run the code and check its output −

Character Pointers and Functions in C

Example

Alternatively, pass ptr to printf() with %s format to print the string.

#include <stdio.h>

int main(){

   char arr[] = "Character Pointers and Functions in C";
   char *ptr = arr;

   printf("%s", ptr);
}

Output

On running this code, you will get the same output −

Character Pointers and Functions in C

Character Pointer Functions

The "string.h" header files defines a number of library functions that perform string processing such as finding the length of a string, copying a string and comparing two strings. These functions use char pointer arguments.

The strlen() Function

The strlen() function returns the length, i.e. the number of characters in a string. The prototype of strlen() function is as follows −

int strlen(char *)

Example 1

The following code shows how you can print the length of a string −

#include <stdio.h>
#include <string.h>

int main(){

   char *ptr = "Hello";

   printf("Given string: %s \n", ptr);
   printf("Length of the string: %d", strlen(ptr));

   return 0;
}

When you run this code, it will produce the following output −

Given string: Hello 
Length of the string: 5

Example 2

Effectively, the strlen() function computes the string length as per the user-defined function str_len() as shown below −

#include <stdio.h>
#include <string.h>

int str_len(char *);

int main(){

   char *ptr = "Welcome to Tutorialspoint";
   int length = str_len(ptr);
   printf("Given string: %s \n", ptr);
   printf("Length of the string: %d", length);
   
   return 0;
}

int str_len(char *ptr){
   int i = 0;
   while(*ptr != '\0'){
      i++;
      ptr++;
   }
   return i;
}

When you run this code, it will produce the following output −

Given string: Welcome to Tutorialspoint 
Length of the string: 25

The strcpy() Function

The assignment operator ( = ) is not used to assign a string value to a string variable, i.e., a char pointer. Instead, we need to use the strcpy() function with the following prototype −

char * strcpy(char * dest, char * source);

Example 1

The following example shows how you can use the strcpy() function −

#include <stdio.h>
#include <string.h>

int main(){

   char *ptr = "How are you doing?";
   char *ptr1;

   strcpy(ptr1, ptr);
   printf("%s", ptr1);

   return 0;
}

The strcpy() function returns the pointer to the destination string ptr1.

How are you doing?

Example 2

Internally, the strcpy() function implements the following logic in the user-defined str_cpy() function

#include <stdio.h>
#include <string.h>

void str_cpy(char *d, char *s);

int main(){

   char *ptr = "Using the strcpy() Function";
   char *ptr1;

   str_cpy(ptr1, ptr);
   printf("%s", ptr1);
   return 0;
}

void str_cpy(char *d, char *s){
   int i;
   for(i = 0; s[i] != '\0'; i++)
      d[i] = s[i];

   d[i] = '\0';
}

When you runt his code, it will produce the following output −

Using the strcpy() Function

The function copies each character from the source string to the destination till the NULL character "\0" is reached. After the loop, it adds a "\0" character at the end of the destination array.

The strcmp() Function

The usual comparison operators (<, >, <=, >=, ==, and !=) are not allowed to be used for comparing two strings. Instead, we need to use strcmp() function from the "string.h" header file. The prototype of this function is as follows −

int strcmp(char *str1, char *str2)

The strcmp() function has three possible return values

  • When both strings are found to be identical, it returns "0".
  • When the first not-matching character in str1 has a greater ASCII value than the corresponding character in str2, the function returns a positive integer. It implies that str1 appears after str2 in alphabetical order, as in a dictionary.
  • When the first not-matching character in str1 has a lesser ASCII value than the corresponding character in str2, the function returns a negative integer. It implies that str1 appears before str2 in alphabetical order, as in a dictionary.

Example 1

The following example demonstrates how you can use the strcmp() function in a C program −

#include <stdio.h>
#include <string.h>

int main(){

   char *s1 = "BASK";
   char *s2 = "BALL";

   int ret = strcmp(s1, s2);

   if (ret == 0)
      printf("Both strings are identical\n");
   else if (ret > 0)
      printf("The first string appears after the second string \n");
   else
      printf("The first string appears before the second string \n");

   return 0;
}

Run the code and check its output −

The first string appears after the second string

Change s1 to BACK and run the code again. Now, you will get the following output

The first string appears before the second string

Example 2

You can obtain a similar result using the user-defined function str_cmp(), as shown in the following code −

#include <stdio.h>
#include <string.h>

int str_cmp(char *str1, char *str2);

int main(){

   char *s1 = "The Best C Programming Tutorial Available Online";
   char *s2 = "The Best C Programming Tutorial Available Online";

   int ret = str_cmp(s1, s2);

   if (ret == 0)
      printf("Both strings are identical\n");
   else if (ret > 0)
      printf("The first string appears after the second string\n");
   else
      printf("The first string appears before the second string\n");

   return 0;
}

int str_cmp(char *str1, char *str2) {
   while (*str1 != '\0' && *str2 != '\0') {
      if (*str1 != *str2) {
         return *str1 - *str2;
      }
      str1++;
      str2++;
   }

   // If both strings are equal, return 0
   
   return 0;
}

When you run this code, it will produce the following output −

Both strings are identical

The str_cmp() function compares the characters at the same index in a string till the characters in either string are exhausted or the characters are equal.

At the time of detecting unequal characters at the same index, the difference in their ASCII values is returned. It returns "0" when the loop is terminated.

Advertisements