String Literals Operations using Pointers in C

What is a String Literal in C?

A string literal in C is a sequence of characters enclosed in double quotes. For example:

"Quiz" // stored as {'Q', 'u', 'i', 'z', '\0'}

Behind the scenes, C stores this string as an array of characters that ends with a null character (\0).

Declaring String Literals with Pointers

String literals can be accessed using pointers, which point to the first character of the string.

#include <stdio.h>
 
int main() {
    const char *str = "Sanfoundry";
    printf("%s\n", str);
    return 0;
}

In this example, str is a pointer to the string literal “Sanfoundry”. The const qualifier indicates that the string should not be modified, as altering string literals leads to undefined behavior.

Accessing Characters via Pointers

You can access individual characters in a string literal using pointer arithmetic.

advertisement
#include <stdio.h>
 
int main() {
    const char *str = "Sanfoundry Quiz";
    printf("First character: %c\n", *str);       // 'S'
    printf("Second character: %c\n", *(str + 1)); // 'a'
    return 0;
}

Here, *str accesses the first character, while *(str + 1) accesses the second character.

Pointer Operations on String Literals

Traversing a String Literal

You can traverse a string using a pointer:

Free 30-Day Python Certification Bootcamp is Live. Join Now!
#include <stdio.h>
 
int main() {
    char *ptr = "Sanfoundry Certification";
    while (*ptr != '\0') {
        printf("%c ", *ptr);
        ptr++;
    }
    return 0;
}

Output:

S a n f o u n d r y   C e r t i f i c a t i o n

This C program prints each character of the string “Sanfoundry Certification” one by one. It uses a pointer ptr to point to the string. The while loop checks if the current character is not the null terminator (‘\0’). If true, it prints the character followed by a space, then moves the pointer to the next character. This continues until the end of the string is reached.

Comparing Two String Literals Using Pointers

#include <stdio.h>
 
int main() {
    char *str1 = "Sanfoundry";
    char *str2 = "Sanfoundry";
 
    if (str1 == str2)
        printf("Pointers are equal\n");
    else
        printf("Pointers are different\n");
 
    return 0;
}

This C program compares two string pointers, str1 and str2, both pointing to the string “Sanfoundry”. Since string literals are often stored in the same memory location, both pointers may point to the same address. The if statement checks if str1 and str2 are equal (i.e., point to the same location). If they do, it prints “Pointers are equal”; otherwise, it prints “Pointers are different”.

Passing a String Literal to a Function

#include <stdio.h>
 
void printQuiz(const char *msg) {
    while (*msg)
        putchar(*msg++);
}
 
int main() {
    printQuiz("Sanfoundry Quiz\n");
    return 0;
}

Output:

Sanfoundry Quiz

This C program prints a string character by character using a custom function. The printQuiz() function takes a pointer to a string and uses a while loop to print each character using putchar() until it reaches the null terminator. In main(), it calls printQuiz() with the message “Sanfoundry Quiz\n”, which gets printed to the screen one character at a time.

advertisement

Modifying String Literals

Trying to Modify a String Literal (Wrong Way)

#include <stdio.h>
 
int main() {
    char *str = "Sanfoundry";
    str[0] = 'X'; // Undefined Behavior
    printf("%s", str);
    return 0;
}

Output:
This causes segmentation fault or crash, because string literals are stored in read-only memory.

Correct Way: Use Character Array for Modification

#include <stdio.h>
 
int main() {
    char str[] = "Sanfoundry";  // Stored in writable memory
    str[0] = 'Q';
    printf("%s\n", str);
    return 0;
}

Output:

Qanfoundry

This C program safely modifies a string stored in writable memory. The array str[] = “Sanfoundry” creates a modifiable copy of the string in memory. It changes the first character from ‘S’ to ‘Q’ using str[0] = ‘Q’. Then, it prints the updated string “Qanfoundry” using printf().

Counting the Length of a String Literal Using Pointers in C

In C, you can count the length of a string literal manually using pointer traversal.

Example:

#include <stdio.h>
 
int main() {
    const char *quiz = "Sanfoundry Certification Quiz";
    const char *ptr = quiz;
    int length = 0;
 
    while (*ptr != '\0') {
        length++;
        ptr++;
    }
 
    printf("Length of string \"%s\" is: %d\n", quiz, length);
    return 0;
}

Output:

Length of string "Sanfoundry Certification Quiz" is: 30

This C program calculates the length of a string manually. It uses a pointer ptr to traverse the string “Sanfoundry Certification Quiz” one character at a time. A counter length increases with each character until the null terminator is reached. Finally, it prints the total length of the string using printf().

Understanding const with Pointers

Using const with pointers helps prevent accidental modifications:

const char *str = "ReadOnly"; // Pointer to constant data
char *const ptr = buffer;     // Constant pointer to data
  • const char *str means the data pointed to by str is constant.
  • char *const ptr means the pointer ptr itself is constant.

Combining both:

const char *const str = "Immutable";

Here, neither the pointer nor the data it points to can be modified.

Best Practices

  • Avoid Modifying String Literals: Always treat string literals as read-only.
  • Use const Qualifiers: Protect string literals by using const with pointers.
  • Copy Before Modification: If you need to modify a string, copy it into a character array first.
  • Be Mindful of Memory: Ensure that destination arrays are large enough to hold copied strings, including the null terminator.

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

If you wish to look at all C Tutorials, go to C Tutorials.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 40s–60s and exploring new directions in your career, I also offer mentoring. Learn more here.