Character Pointer in C 

Character Pointer in C Language with Examples

In this article, I will discuss Character Pointers in C Language with Examples. Please read our previous articles discussing Passing Pointers to Function in C Language with Examples. At the end of this article, you will understand what Character Pointer is, why we need Character Pointers, and how to create Character Pointers in C Language.

Character Pointer in C Language:

In C programming, a character pointer points to a character data type. This type of pointer is commonly used for dealing with strings (arrays of characters) because, in C, strings are represented as arrays of characters terminated by a null character (‘\0’). Understanding character pointers is crucial for effective C string manipulation and memory management.

Key Points:
  • Character pointers are essential for string manipulation in C.
  • Be cautious with string literals, as they are read-only. Attempting to modify a string literal via a pointer will cause undefined behavior.
  • You can use character pointers to traverse and manipulate strings.
  • Understanding the difference between a string literal and a character array is crucial when working with character pointers.

Let’s see multiple examples to understand how character pointers are used in various scenarios.

Example: Pointing to a Single Character
#include <stdio.h>

int main() {
    char ch = 'A';
    char *char_ptr = &ch; // Pointer to a character

    printf("Value of ch: %c\n", *char_ptr); // Dereferencing the pointer

    return 0;
}

In this example, char_ptr is a pointer to a character variable ch.

Example: Pointing to a String Literal Using Character in C
#include <stdio.h>

int main() {
    char *str = "Hello, world!"; // Pointer to a string literal

    printf("String: %s\n", str);

    return 0;
}

Here, str is a pointer to the first character of the string literal “Hello, world!”. Remember, string literals are immutable, so attempting to modify them (like str[0] = ‘h’;) leads to undefined behavior.

Example: Traversing a String with a Pointer
#include <stdio.h>

int main() {
    char str[] = "Hello";
    char *ptr = str; // Pointer to the first character of the array

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

    printf("\n");

    return 0;
}

In this example, ptr traverses and prints each character in the string str.

Example 4: Modifying a String Array Using Pointers
#include <stdio.h>

int main() {
    char str[] = "Hello"; // Array of characters
    char *ptr = str;

    ptr[1] = 'a'; // Modify the second character

    printf("Modified string: %s\n", str); // Prints "Hallo"

    return 0;
}

Since str is an array, it can be modified. The pointer ptr is used to change the second character of str.

Example: Function to Calculate String Length Using Character Pointers
#include <stdio.h>

size_t stringLength(const char *str) {
    const char *ptr = str;

    while (*ptr) // Iterate until null character
        ptr++;

    return ptr - str; // Difference gives the length
}

int main() {
    char *str = "Hello";
    printf("Length of the string: %zu\n", stringLength(str));

    return 0;
}

This function calculates the length of a string by using a character pointer to traverse the string until the null character \0 is encountered.

Example: Dynamic Memory Allocation

Character pointers are often used with dynamic memory allocation for strings:

#include <stdio.h>
#include <stdlib.h>

int main() {
    char *str = (char *)malloc(50 * sizeof(char)); // Allocate memory for 50 characters

    if (str != NULL) {
        strcpy(str, "Dynamic String");
        printf("%s\n", str);

        free(str);  // Don't forget to free the memory
    }

    return 0;
}

In this example, str is a pointer to a dynamically allocated block of memory, large enough to hold a string of 49 characters plus the null terminator.

Points to Remember:
  • When using character pointers, especially with dynamic memory, it’s crucial to ensure you don’t access memory outside the allocated range. This can lead to undefined behavior.
  • Ensure that strings are null-terminated, as many string-handling functions in C rely on this.
  • Read-Only vs. Modifiable: Understand the difference between pointing to a string literal (read-only) and pointing to a character array (modifiable).
  • Memory Management: Be cautious with dynamic memory allocation and ensure proper memory deallocation to avoid leaks. 
  • When using dynamically allocated memory, make sure to free the allocated memory using free() to avoid memory leaks.
  • Safety and Stability: Incorrect use of character pointers can lead to errors like segmentation faults, especially when dealing with uninitialized pointers, null pointers, or going beyond the bounds of the string.
When to Use Character Pointer in C?

Using a character pointer in C is particularly beneficial in several scenarios. Understanding when and how to use character pointers is crucial for efficient and effective C programming, especially in string manipulation and memory management. Here are some common situations where you would use a character pointer:

  • Handling String Literals: You often use character pointers when working with string literals. For example, char *str = “Hello World”; creates a pointer str that points to the first character of the string literal. Remember, string literals are stored in read-only memory, so they should not be modified.
  • Dynamic Strings: If you need to create strings whose size is not known at compile time or that can change during program execution, you use character pointers with dynamic memory allocation functions like malloc and realloc.
  • Passing Strings to Functions: It’s more efficient to pass a pointer to a character array (string) to a function rather than passing the whole array. This way, the function can work with the original string without creating a copy.
  • Modifying Strings in Functions: If you need to modify a string in a function, you pass a character pointer to the function. This allows the function to modify the original string.
  • Memory Efficiency: Using character pointers instead of character arrays can save memory, especially when dealing with large strings or a large number of strings, as pointers are usually smaller in size than arrays.
  • Handling Arrays of Strings: When dealing with arrays of strings (e.g., command-line arguments), character pointers are used to create arrays of pointers, with each pointer pointing to a different string.
  • Reading and Writing Strings: In operations involving I/O, like reading from or writing to files, network sockets, etc., character pointers are used to point to buffers (character arrays) where the data is read into or written from.
  • Defining String Constants: For defining constants that won’t change during the execution of the program, character pointers to string literals are often used.

In the next article, I will discuss Pointer to Constant in C Language with Examples. In this article, I try to explain the Character Pointer in C Language with Examples. I hope you enjoy this article. I would like to have your feedback. Please post your feedback, questions, or comments about this article.

Leave a Reply

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