For working professionals
For fresh graduates
More
5. Array in C
13. Boolean in C
18. Operators in C
33. Comments in C
38. Constants in C
41. Data Types in C
49. Double In C
58. For Loop in C
60. Functions in C
70. Identifiers in C
81. Linked list in C
83. Macros in C
86. Nested Loop in C
97. Pseudo-Code In C
100. Recursion in C
103. Square Root in C
104. Stack in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
If you're learning C, you've probably come across the term "pointer." And if you're working with text, you'll quickly find that understanding how pointers work with strings is really important. String pointers in C are just arrays of characters that end with a special character called the null terminator (\0). There’s no special string type like in other modern languages.
Because of this, you’ll find string pointers in C, which are a crucial part of every software development course. Every professional developer utilizes this concept in numerous real-world applications.
In this blog, we’ll break down how a string pointer in C works, how to create one, how to use it to access and modify text, and how it behaves differently compared to character arrays. Every example is explained step-by-step with output and a detailed breakdown of how the code works.
Must Explore: Introduction to C Tutorial
In this section, we’ll look at how to define strings using character arrays and pointers to string literals. This helps establish the difference between mutable and immutable strings in C.
#include <stdio.h>
int main() {
// Declare and initialize a character array with a string
// This automatically appends a null character '\0' at the end
char str1[] = "Hello";
// Print the string to the console using %s format specifier
printf("%s\n", str1);
return 0;
}
Output:
Hello
Must Read: 29 C Programming Projects in 2025 for All Levels [Source Code Included]
#include <stdio.h>
int main() {
// Declare a pointer to a string literal
char *str2 = "World";
// Print the string using the pointer
printf("%s\n", str2);
return 0;
}
Output:
World
You should not modify str2.
Also Explore: What are Data Structures in C & How to Use Them?
This section demonstrates how to use pointers to reference either string literals or character arrays, explaining how memory handling differs.
#include <stdio.h>
int main() {
// Initialize a pointer with a string literal
char *ptr = "Pointer to string";
// Print the full string using the pointer
printf("%s\n", ptr);
return 0;
}
Output:
Pointer to string
#include <stdio.h>
int main() {
// Declare a modifiable character array
char str[] = "Change Me";
// Pointer points to the base address of the array
char *ptr = str;
// Modify the first character of the string using pointer
ptr[0] = 'R';
// Output the updated string
printf("%s\n", str);
return 0;
}
Output:
Range Me
Also Explore Doctor of Business Administration for High-End Career Advancement
In this part, we access and manipulate strings using pointer dereferencing and arithmetic.
#include <stdio.h>
int main() {
char str[] = "Pointer"; // define the string
char *p = str; // pointer to start of string
// Traverse each character until null terminator is hit
while (*p != '\0') {
printf("%c ", *p); // print current character
p++; // move pointer to next character
}
return 0;
}
Output:
P o i n t e r
#include <stdio.h>
int main() {
char str[] = "Index"; // string to access
char *p = str; // pointer to string
// Print third character using offset
printf("Third character: %c\n", *(p + 2));
return 0;
}
Output:
Third character: d
Check out the Executive Diploma in Data Science & AI with IIIT-B!
This section shows how to dynamically allocate memory for strings, allowing flexible input and safe storage.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char *name = (char *)malloc(25); // allocate memory for string
strcpy(name, "Dynamic String"); // copy content to memory
printf("%s\n", name); // output string
free(name); // release memory
return 0;
}
Output:
Dynamic String
Pursue Best Artificial Intelligence and Machine Learning Course
#include <stdio.h>
#include <stdlib.h>
int main() {
char *input = (char *)malloc(50); // allocate space
printf("Enter text: ");
fgets(input, 50, stdin); // read input from user
printf("You typed: %s", input); // print what was typed
free(input); // free the memory
return 0;
}
Output (sample):
Enter text: Hello GPT
You typed: Hello GPT
This section demonstrates how to store multiple strings using arrays of pointers or character arrays. Here, we’ll be using for loops concept.
#include <stdio.h>
int main() {
char *fruits[] = {"Apple", "Banana", "Cherry"}; // pointer array
for (int i = 0; i < 3; i++) {
printf("%s\n", fruits[i]); // print each string
}
return 0;
}
Output:
Apple
Banana
Cherry
#include <stdio.h>
int main() {
char cities[3][10] = {"Paris", "London", "Tokyo"};
for (int i = 0; i < 3; i++) {
printf("%s\n", cities[i]); // print each city
}
return 0;
}
Output:
Paris
London
Tokyo
Pursue DBA in Digital Leadership from Golden Gate University, San Francisco!
This final example summarizes static, literal, and dynamic string usage in a single program.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char staticStr[] = "Static"; // modifiable array
char *literalStr = "Literal"; // read-only literal
char *dynamicStr = (char *)malloc(30); // dynamic allocation
strcpy(dynamicStr, "Dynamic Memory"); // copy string
printf("Array: %s\n", staticStr);
printf("Pointer to literal: %s\n", literalStr);
printf("Dynamically allocated: %s\n", dynamicStr);
free(dynamicStr); // clean up
return 0;
}
Output:
Array: Static
Pointer to literal: Literal
Dynamically allocated: Dynamic Memory
Working with string pointer in C gives you a lot of flexibility—but it also requires careful handling. Here are some common mistakes to watch out for:
1. Trying to Modify a String Literal
char *str = "Hello";
str[0] = 'h'; // undefined behavior
String literals are stored in read-only memory. Modifying them can cause your program to crash or behave unexpectedly.
2. Forgetting to Allocate Memory Before Use
char *str;
strcpy(str, "Hi"); // dangerous: str is uninitialized
Always allocate memory using `malloc()` or point it to valid memory before using it.
3. Not Freeing Dynamically Allocated Memory
If you use `malloc()`, you must call `free()` once you're done to avoid memory leaks.
4. Missing the Null Terminator
Manually building a string? Don't forget the `\\0` at the end, or you'll overrun memory when printing.
5. Buffer Overflow
Writing beyond allocated space can corrupt memory. Always ensure you don't copy more characters than your buffer can hold.
6. Confusing Arrays and Pointers
Remember: arrays are not the same as pointers, even though they can behave similarly. Misunderstanding this can lead to hard-to-find bugs.
Understanding how to use a string pointer in C opens the door to many real-world programming tasks. Here are a few practical examples:
1. Command-Line Arguments
The `main` function can take `char *argv[]`, which is an array of string pointers. This is how you process input passed to your program.
int main(int argc, char *argv[]) {
printf(\"Program name: %s\\n\", argv[0]);
return 0;
}
2. File I/O and Text Buffers
When reading files, you use string pointers to store and manipulate lines of text.
3. Dynamic Input from Users
Many real-world programs need to accept unknown-length input. `malloc` + string pointers help handle that safely.
4. Custom String Libraries
Embedded systems and performance-critical applications often roll out their own string functions using pointers for speed and control.
5. Parsing and Tokenization
In interpreters or compilers, you often break strings into tokens using pointer manipulation for efficiency.
6. Network Protocols and Message Buffers
Network programs build and parse packets (which are often strings) using pointers to manage memory manually.
Understanding how to use a string pointer in C is a key step in mastering the language. Strings in C are handled very differently from higher-level languages, and getting comfortable with pointers gives you greater control, flexibility, and efficiency. Whether you're accessing each character of a string, dynamically allocating memory, or managing arrays of strings, string pointers help you write powerful and memory-efficient programs.
By practicing the examples and avoiding common pitfalls, you'll be better equipped to handle real-world problems where string manipulation is critical—like parsing user input, reading files, or building command-line tools. As with all pointer-related concepts in C, attention to detail matters. Keep experimenting, stay curious, and over time, the string pointer in C will become a natural and trusted part of your programming toolkit.
C treats string literals as constants because they are shared across the program for efficiency. Allowing modifications could lead to unpredictable behavior or security issues since multiple pointers might refer to the same literal.
You should copy the string literal into a writable array using strcpy() or use malloc() to allocate memory, then copy the content. Never attempt to modify the original literal directly.
Yes, in many cases. Since pointers allow direct memory access and pointer arithmetic, they can be more efficient than array indexing, especially in loops and low-level operations.
const char* means the string data should not be modified through the pointer, while char* allows modification. This distinction helps protect string literals and avoid accidental changes.
Yes. If a string is defined as a local character array, a pointer can refer to it. However, once the function ends, that memory is lost, and the pointer becomes invalid.
Functions like printf, strlen, and strcpy rely on the null terminator to know where the string ends. Omitting it can cause buffer overflows or read garbage memory.
Yes, but you should be careful. You can return a pointer to a string allocated with malloc or a global/static variable. Never return a pointer to a local array—it becomes invalid after the function exits.
A 2D character array reserves fixed space for each string, while an array of string pointers allows variable-length strings and is more memory efficient, especially when strings differ in length.
Absolutely. Functions like strlen(), strcpy(), strcat(), and strcmp() accept string pointers because they operate on addresses, not raw arrays. This flexibility is central to C’s design.
Yes. It's common in C to use char* in structures to hold names, messages, or any string data. Just ensure you allocate or assign memory correctly before using it.
Declaring a function parameter as const char* tells the caller the function will not (and should not) modify the string. It’s good practice when passing string literals or read-only data.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.