0
0
CHow-ToBeginner · 3 min read

How to Create String Using Pointer in C: Simple Guide

In C, you can create a string using a char pointer by assigning it to a string literal like char *str = "Hello";. This pointer points to the first character of the string stored in read-only memory, allowing you to use the string without copying it.
📐

Syntax

To create a string using a pointer in C, you declare a char pointer and assign it a string literal. The pointer then points to the first character of the string.

  • char *str: declares a pointer to a character.
  • "Hello": a string literal stored in read-only memory.
  • Assignment links the pointer to the string's first character.
c
char *str = "Hello";
💻

Example

This example shows how to create a string using a pointer and print it. It demonstrates that the pointer points to the string literal and can be used like a normal string.

c
#include <stdio.h>

int main() {
    char *str = "Hello, world!";
    printf("%s\n", str);
    return 0;
}
Output
Hello, world!
⚠️

Common Pitfalls

Common mistakes include trying to modify a string literal through a pointer, which causes undefined behavior because string literals are stored in read-only memory. Also, forgetting that the pointer does not own the memory can lead to errors if the pointer is used after the string goes out of scope.

Correct way: use const char * if you don't plan to modify the string.

c
/* Wrong: Modifying string literal - causes error */
char *str = "Hello";
str[0] = 'h'; // Undefined behavior

/* Right: Use const pointer to avoid modification */
const char *str2 = "Hello";
// str2[0] = 'h'; // Compiler error prevents modification
📊

Quick Reference

ConceptDescription
char *str = "text";Pointer to a string literal (read-only)
const char *str;Pointer to a constant string to prevent modification
char str[] = "text";Array of chars initialized with string (modifiable)
Modifying string literalUndefined behavior, avoid it
Pointer points to first charUse %s in printf to print the string

Key Takeaways

Use a char pointer assigned to a string literal to create a string in C.
String literals are stored in read-only memory; do not modify them through pointers.
Use const char * to indicate the string should not be changed.
To have a modifiable string, use a char array instead of a pointer.
Always use %s in printf to print strings pointed to by char pointers.