0
0
CHow-ToBeginner · 3 min read

How to Use Pointer with String in C: Simple Guide

In C, a string is an array of characters ending with a null character \0. You can use a char * pointer to point to the first character of the string and access or modify it by moving the pointer along the characters.
📐

Syntax

To use a pointer with a string in C, declare a pointer of type char * and assign it the address of a string literal or a character array. You can then access characters by dereferencing the pointer or using pointer arithmetic.

  • char *ptr = "Hello"; — pointer to string literal
  • char arr[] = "Hello"; — character array
  • ptr = arr; — pointer points to array start
c
char *ptr = "Hello";

// Access first character
char first = *ptr;

// Access second character
char second = *(ptr + 1);
💻

Example

This example shows how to use a pointer to print each character of a string one by one by moving the pointer forward.

c
#include <stdio.h>

int main() {
    char *str = "Hello, world!";
    while (*str != '\0') {
        printf("%c", *str);
        str++; // Move pointer to next character
    }
    printf("\n");
    return 0;
}
Output
Hello, world!
⚠️

Common Pitfalls

Common mistakes when using pointers with strings include:

  • Trying to modify a string literal through a pointer, which causes undefined behavior.
  • Not ensuring the string ends with a null character \0, leading to reading garbage or crashes.
  • Forgetting to increment the pointer to move through the string.

Always use a character array if you want to modify the string.

c
/* Wrong: Modifying string literal (undefined behavior) */
char *str = "Hello";
str[0] = 'J'; // Not allowed

/* Right: Using character array to modify */
char arr[] = "Hello";
arr[0] = 'J'; // Allowed
📊

Quick Reference

  • Pointer declaration: char *ptr;
  • Assign string literal: ptr = "text";
  • Assign array: ptr = arr;
  • Access char: *ptr or ptr[index]
  • Move pointer: ptr++ to next char
  • Modify string: Use char arr[], not string literal

Key Takeaways

Use char * pointer to point to the first character of a string.
String literals are read-only; use character arrays to modify strings.
Move the pointer with ptr++ to access each character sequentially.
Always ensure strings end with a null character \0.
Access characters by dereferencing the pointer or using array-like syntax.