Pointer and strings
- Siddharth Sharma
- Nov 8, 2024
- 4 min read
Pointers are commonly used with strings in C and C++, providing a flexible and efficient way to handle text data. Strings in C are represented as arrays of characters, typically ending with a null character ('\0'), which indicates the end of the string. Pointers play a key role in manipulating these character arrays.
Basic Concepts of Pointers and Strings
In C, a string can be represented in two primary ways:
As a character array, e.g., char str[] = "Hello";
As a pointer to a character, e.g., char *str = "Hello";
Both forms can be used interchangeably in many situations, but they differ in terms of mutability and memory allocation.
Example 1: String as a Character Array
#include <stdio.h>
int main() {
char str[] = "Hello"; // Character array
printf("String: %s\n", str); // Output: Hello
printf("First character: %c\n", str[0]); // Output: H
str[0] = 'M'; // Modify the array (allowed)
printf("Modified String: %s\n", str); // Output: Mello
return 0;
}Explanation:
char str[] = "Hello"; declares a character array and initializes it with the string "Hello".
The array can be modified, and the change affects only str since it occupies a unique memory block.
Example 2: String as a Pointer to a Constant String Literal
#include <stdio.h>
int main() {
const char *str = "Hello"; // Pointer to a constant string literal
printf("String: %s\n", str); // Output: Hello
printf("First character: %c\n", str[0]); // Output: H
// str[0] = 'M'; // Error: Cannot modify a string literal
return 0;
}Explanation:
const char *str = "Hello"; declares a pointer to a constant string literal.
Attempting to modify str[0] will result in a compilation error, as string literals are stored in read-only memory.
Using Pointers to Traverse Strings
Pointers allow you to navigate through a string's characters efficiently.
Example: Traversing a String Using a Pointer
#include <stdio.h>
int main() {
const char *str = "Hello, World!";
const char *ptr = str; // Pointer initialized to the start of the string
while (*ptr != '\0') { // Loop until the null character is found
printf("%c", *ptr); // Dereference the pointer to get the character
ptr++; // Move the pointer to the next character
}
printf("\n");
return 0;
}Explanation:
const char *ptr = str; initializes a pointer to the start of the string.
while (*ptr != '\0') iterates over each character in the string until the null character is reached.
ptr++ advances the pointer to the next character.
Pointer Arithmetic with Strings
Pointers allow you to perform arithmetic to access different parts of a string. Each increment of the pointer moves it to the next character in the string.
Example: Accessing Specific Characters
#include <stdio.h>
int main() {
const char *str = "Hello, World!";
printf("First character: %c\n", *str); // Output: H
printf("Second character: %c\n", *(str + 1)); // Output: e
printf("Sixth character: %c\n", *(str + 5)); // Output: ,
return 0;
}Explanation:
(str + 1) accesses the second character ('e'), and (str + 5) accesses the sixth character (',').
Passing Strings to Functions Using Pointers
Passing strings to functions in C is typically done using pointers, as passing arrays directly is not supported.
Example: Function that Prints a String
#include <stdio.h>
void printString(const char *str) {
while (*str != '\0') {
printf("%c", *str);
str++;
}
printf("\n");
}
int main() {
const char *greeting = "Hello, World!";
printString(greeting); // Pass the pointer to the function
return 0;
}Explanation:
The printString function takes a const char* parameter, allowing it to receive any string (pointer to char).
It iterates over each character in the string and prints it until reaching the null character.
Array of String Pointers
You can create an array of pointers to strings, which is useful for storing lists of strings, like names or messages.
Example: Array of String Pointers
#include <stdio.h>
int main() {
const char *colors[] = {"Red", "Green", "Blue", "Yellow"};
for (int i = 0; i < 4; i++) {
printf("Color[%d]: %s\n", i, colors[i]);
}
return 0;
}Explanation:
const char *colors[] is an array of string pointers, where each element points to a string literal (e.g., "Red", "Green").
You can access each string with colors[i], and print it using %s format specifier.
Modifying Strings Using Character Arrays vs. String Literals
When using a character array (char str[]), you can modify the string contents. When using a pointer to a string literal (const char *str), the string is usually immutable.
Example: Mutable and Immutable Strings
#include <stdio.h>
int main() {
char str1[] = "Hello"; // Mutable string (modifiable)
const char *str2 = "World"; // Immutable string (string literal)
str1[0] = 'M'; // Allowed
// str2[0] = 'W'; // Not allowed, causes an error
printf("Modified str1: %s\n", str1); // Output: Mello
printf("str2: %s\n", str2); // Output: World
return 0;
}Summary
String as a Character Array: char str[] = "text"; creates a mutable string.
String as a Pointer to Literal: const char *str = "text"; creates a pointer to an immutable string literal.
Pointer Arithmetic: Pointers allow you to move through the string by incrementing or decrementing the pointer.
Function Parameters: Strings are passed to functions as const char* to indicate a pointer to the first character of the string.
Array of String Pointers: const char *arr[] = {"text1", "text2"}; is used for lists of strings.
Using pointers with strings in C enables efficient handling of text and allows easy manipulation of text data, though care must be taken with string literals and memory safety.
4o




Comments