String using Pointers in C

Get Certified in C Programming for Free and Take Your Skills to the Next Level

Strings are an essential component of any programming language. A string is defined in C as a group of characters that are all followed by the null character “0.” Character arrays are provided by C for storing strings. However, directly accessing and manipulating strings using arrays can be cumbersome. This is where string pointers come into the picture.

Pointers provide an efficient way to access and modify strings by directly pointing to characters in a string. In this article, we will learn how to declare, initialize and manipulate strings using pointers in C.

String introduction

Termination of strings in C

The special null character 0 is used to indicate the end of a string in C. As a result, commands like printf() and puts() can print the string correctly up until the termination character.

Termination of strings

Use of pointers in C

Pointers are special variables that store the memory address of other variables. They can be used to directly access and modify the content stored in that memory address. This makes them useful for efficiently manipulating strings.

Use of pointers

2D arrays and pointer variables in C

Two-dimensional arrays and pointer variables can be used to store multiple strings by allocating memory dynamically. However, they have certain limitations in terms of flexibility and memory utilization.

Creating a String

We can declare a character array to store a string in C. The general syntax is:

char str[size];

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

For example, to store the string “String”:

char str[7] = "DataFlair";

Note that we allocate 6 characters to store the 5-character string “String” plus the null terminator \0. The compiler automatically appends the null character at the end.

We can also initialize strings using string literals enclosed in double quotes:

char str[] = "DataFlair";

Here, the size of the array is automatically set based on the size of the string literal.

If we declare the array size equal to the string length, the null terminator will be missing. This can cause undefined behavior when trying to print or traverse the string.

char str[5] = "String"; // Missing null terminator

Creating a Pointer to the String

The first element in an array’s name corresponds to its memory location so that we can establish a pointer to the string’s initial character.

char *ptr = str; // ptr points to first char of str

To create a pointer to “String”:

char str[] = "String";
char *ptr = str;

Now ptr points to the first character ‘S’ of the string “String”.

Creating a Pointer to the String

Creating a Pointer to the String chart

Accessing String via Pointer

We can access individual characters using the dereference operator *.

For example:

*ptr = 'S';
x = *ptr; // x contains 'S'

To print all characters of the string using the pointer:

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

This loops through and prints each character until the null terminator is encountered.

Accessing String via Pointer

#include <stdio.h>

int main() {
    // Declare a string
    char str[] = "Hello, World!";

    // Initialize a pointer to the beginning of the string
    char *ptr = str;

    // Iterate through the string using the pointer
    while (*ptr != '\0') {
        printf("%c ", *ptr);
        ptr++; // Move the pointer to the next character
    }

    printf("\n");

    return 0;
}

Output:
H e l l o , W o r l d !

Using a Pointer to Store String

We can also use a pointer to store a string:

char *str = "HelloWorld";

The initial character of the string literal, to which str points, is kept in read-only memory. Using printf(“%s”, str), we can print the string.

#include <stdio.h>

int main() {
    // Declare a pointer to a string
    char *str_ptr;

    // Define a string
    char my_string[] = "Hello, World!";

    // Assign the address of the string to the pointer
    str_ptr = my_string;

    // Print the string using the pointer
    printf("String stored in pointer: %s\n", str_ptr);

    return 0;
}

Output:
String stored in pointer: Hello, World!

 

using a pointer to store string

Array of Strings in C

We can store multiple strings using a 2D character array:

char names[2][10] = { "John", "Mary"};

Here, the second dimension stores individual strings. Memory is allocated for the declared size irrespective of the actual string lengths.

To overcome this memory wastage, we can use an array of pointers:

char *names[] = {"John", "Mary"};

Now, memory is allocated dynamically based on string size. We can print individual strings using printf(“%s”, names[i]);

#include <stdio.h>

int main() {
    // Declare a 2D array of strings for books
    char *books[][2] = {
        {"The Catcher in the Rye", "J.D. Salinger"},
        {"To Kill a Mockingbird", "Harper Lee"},
        {"1984", "George Orwell"},
        {"The Great Gatsby", "F. Scott Fitzgerald"},
        {"War and Peace", "Leo Tolstoy"}
    };

    // Print the list of books with titles and authors
    printf("List of Books:\n");
    for (int i = 0; i < 5; i++) {
        printf("%d. Title: %s\n", i + 1, books[i][0]);
        printf("   Author: %s\n", books[i][1]);
    }

    return 0;
}

Output:
List of Books:
1. Title: The Catcher in the Rye
Author: J.D. Salinger
2. Title: To Kill a Mockingbird
Author: Harper Lee
3. Title: 1984
Author: George Orwell
4. Title: The Great Gatsby
Author: F. Scott Fitzgerald
5. Title: War and Peace
Author: Leo Tolstoy

Example Program

Example 1:

Here is an example program to demonstrate string pointers:

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

int main() {
  
  char *names[3];
  
  // Input strings
  names[0] = "John";
  names[1] = "Bob";
  names[2] = "Alice";  

  // Print strings and lengths  
  for(int i=0; i<3; i++) {
     printf("Name = %s, Length = %lu\n", names[i], strlen(names[i]));
  }
  
  return 0;
}

This stores input strings in a pointer array and prints them along with their length using strlen().

Output:
Name = John, Length = 4
Name = Bob, Length = 3
Name = Alice, Length = 5

Time Complexity: O(N)
Auxiliary Space: O(1)

Example 2:

#include <stdio.h>

int main(void) {
  char characterName[] = "DataFlair";

  printf("%c\n", *characterName);
  printf("%c\n", *(characterName + 1));
  printf("%c\n", *(characterName + 7));

  char *namePointer;

  namePointer = characterName;
  printf("%c\n", *namePointer);
  printf("%c\n", *(namePointer + 1));
  printf("%c\n", *(namePointer + 7));

  return 0;
}

Output:
D
a
i
D
a
I

Conclusion

  • Pointers allow direct access to strings for efficient manipulation.
  • Character arrays and pointers can be used to store strings.
  • Two-dimensional arrays and pointer arrays allow for storing multiple strings.
  • Pointer arrays are more flexible and memory-efficient for strings.
  • Learning pointers is crucial for performing string operations in C.

We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *