Pointer String
- A string in C/C++ is an array of characters, and pointers can be used to handle strings efficiently.
- A character pointer (
char *
) points to the first character of a string (character array).
char str[] = "Hello";char *ptr = str; // Pointer points to the first character of the string
cout << ptr[0]; // Outputs 'H'cout << *(ptr + 1); // Outputs 'e'
- Strings are terminated with a null character (‘\0’).
- You can manipulate strings using pointers (e.g., traversing, comparing).
#include <iostream>using namespace std;
void printChars(char *str) { while(*str != '\0') { cout << *str; str++; // Move to the next character }}
int main() { char name[] = "Pointers!"; printChars(name); // Outputs "Pointers!" return 0;}
More Examples:
int arr[5] = {1,2,3,4,5};char ch[6] = "abcde";
cout << arr << endl; // Prints address of arr (e.g., 0x61fefc) // For int arrays, prints address—not the contents!
// attention herecout << ch << endl; // Prints the string "abcde" // For char arrays, prints characters until null terminator
char *c = &ch[0];// prints entire stringcout << c << endl; // Prints the string "abcde" // Points to first character: behaves like "cout << ch"
char temp = 'z';char *p = &temp;
cout << p << endl; // Prints garbage or "z" followed by garbage chars // Interprets memory at p as a string until null terminator is found // This is unsafe/undefined: 'temp' is not null-terminated