Pointers and Strings in C
You can write a string in C in two ways: char s[] = "Hello"; and char *s = "Hello";. They look almost the same, but one of them crashes if you try to change a letter.
In this lesson you will learn how strings and pointers work together: the difference between a char array and a char pointer, how to walk a string with a pointer, and how library functions like strlen and strcpy work inside.
What You Will Learn
- How a char pointer points to a string.
- Char array vs char pointer: the key differences.
- Why string literals are read-only.
- How to walk a string using
*pandp++. - How to find length and copy a string with pointers.
Pointers and Strings Explained
Exam definition: A character pointer (char *) can hold the address of the first character of a string. With char *s = "Hello";, s points to a string literal stored in read-only memory; with char s[] = "Hello";, the characters are copied into an array that can be modified.
Memory trick: char s[] = "Hello" = you photocopy a notice into your own notebook: you can edit your copy. char *s = "Hello" = you only note where the notice board is: the notice belongs to the college; you can read it, not edit it.
char arr[] = "Hi"; char *ptr = "Hi";
arr: |'H'|'i'|'\0'| (your array, ptr: [ address ] ----> |'H'|'i'|'\0'|
editable) (string literal,
read-only memory)
sizeof(arr) = 3 sizeof(ptr) = 8 (64-bit)
Syntax: Char Array vs Char Pointer
char arr[] = "Hello"; /* array of 6 chars, editable */
char *ptr = "Hello"; /* pointer to a read-only literal */
const char *msg = "Hi"; /* best style: const says "don't modify" */
arr[0] = 'J'; /* OK: "Jello" */
ptr[0] = 'J'; /* WRONG: undefined behaviour, usually a crash */
ptr = "World"; /* OK: pointer now points to another literal */
arr = "World"; /* ERROR: array name can't be assigned */
| Point | char arr[] = "Hello" | char *ptr = "Hello" |
|---|---|---|
| Storage | Own array (stack) | Literal in read-only memory + a pointer |
| Change a letter | Yes | No (crash risk) |
| Point to another string | No (use strcpy) | Yes: ptr = "Bye"; |
sizeof | 6 | 8 (pointer size) |
arr++ / ptr++ | Error | Allowed |
Example 1: Walk a String with a Pointer
#include <stdio.h>
int main(void)
{
char city[] = "Mumbai";
char *p = city; /* p points to 'M' */
int length = 0;
printf("Characters:");
while (*p != '\0') /* same as while (*p) */
{
printf(" %c", *p);
p++;
length++;
}
printf("\n");
printf("Length = %d\n", length);
printf("Pointer moved %d places\n", (int)(p - city));
p = city + 3; /* point into the middle */
printf("From index 3: %s\n", p);
return 0;
}
Output
Characters: M u m b a i Length = 6 Pointer moved 6 places From index 3: bai
Code Explanation
char *p = city;makes p point to the first character.*pis the current character. The loop runs until it reaches'\0'. Since'\0'is 0 (false),while (*p)means the same thing.p++moves to the next character (1 byte, since char is 1 byte).p - cityis pointer subtraction: how far p moved, which equals the length.printf("%s", p)prints from wherever p points up to'\0', socity + 3prints "bai".
How String Functions Use Pointers
Library functions like strlen and strcpy take char * parameters. When you pass an array, its base address goes in, and the function walks it with a pointer. The famous one-line copy loop:
while ((*dest++ = *src++) != '\0')
;
*src++reads the current source character, then moves src.*dest++ = ...stores it at dest, then moves dest.- The value of the assignment is the copied character. When it is
'\0', the loop stops, after copying the'\0'too.
Example 2: String Length, Copy and Vowel Count Using Pointers
#include <stdio.h>
int str_length(const char *s)
{
const char *start = s;
while (*s)
s++;
return (int)(s - start);
}
void str_copy(char *dest, const char *src)
{
while ((*dest++ = *src++) != '\0')
;
}
int count_vowels(const char *s)
{
int count = 0;
for (; *s; s++)
{
char c = *s | 32; /* quick lowercase for letters */
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
count++;
}
return count;
}
int main(void)
{
const char *motto = "Education Is Power"; /* read-only literal */
char copy[40];
printf("Text : %s\n", motto);
printf("Length : %d\n", str_length(motto));
printf("Vowels : %d\n", count_vowels(motto));
str_copy(copy, motto); /* copy into an editable array */
copy[0] = 'e'; /* safe: copy is our own array */
printf("Copy : %s\n", copy);
return 0;
}
Output
Text : Education Is Power Length : 18 Vowels : 8 Copy : education Is Power
const char *parameters promise the function won't change the string, so string literals can be passed safely.str_lengthuses two pointers: the end minus the start gives the length.- To modify text that came from a literal, copy it into an array first.
*s | 32turns a capital letter into small (it sets the bit worth 32). It's a common trick;tolowerfrom ctype.h is clearer.
Practice: concatenate two strings using pointer.
Important Points to Remember
char arr[] = "..."makes an editable copy.char *p = "..."points to a read-only literal; prefer const char *.- Walk a string with while (*p) p++;
printf("%s", p)prints from p up to '\0'.- A char pointer can be re-pointed; an array name can't.
- Length with pointers = end − start.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
char *s = "abc"; s[0] = 'x'; | Crash (segmentation fault) | char s[] = "abc"; |
char *s; scanf("%s", s); | Writes to a random address | char s[50]; or malloc first |
strcpy(p, "Hi") where p points to a literal | Crash | Copy into an array |
Losing the start after p++ | Can't print the whole string again | Use a second pointer to walk |
if (p == "yes") | Compares addresses | strcmp(p, "yes") == 0 |
Pointers and Strings Practice Questions
- What is the difference between
char s[] = "C"andchar *s = "C"? - Why does changing a character of a string literal crash?
- What does
printf("%s", s + 2)print ifsholds "Kolkata"? - Write a loop that moves a pointer
pto the end of a string. - Why do string function parameters use
const char *?
Show answers
- The first is an editable 2-byte array; the second is a pointer to a read-only literal (sizeof 8 on 64-bit).
- String literals are stored in read-only memory; writing there is undefined behaviour.
- "lkata".
while (*p) p++;- To promise the function won't modify the string, which also allows passing literals.
Coding Exercise
Using only pointers (no s[i]), write void to_upper(char *s) that converts a string to capitals, and test it on an editable array holding "pointer power".
Show solution
#include <stdio.h>
void to_upper(char *s)
{
while (*s)
{
if (*s >= 'a' && *s <= 'z')
*s = *s - 32;
s++;
}
}
int main(void)
{
char text[] = "pointer power";
to_upper(text);
printf("%s\n", text);
return 0;
}
POINTER POWER
Quick Quiz: Pointers and Strings (MCQ)
-
Which can be modified safely?
A)
char *s = "abc";B)char s[] = "abc";C) Both D) Neither -
char *p = "Delhi"; printf("%c", *(p + 1));prints:A) D B) e C) l D) elhi
-
sizeof(p)forchar *p = "Hello";on 64-bit:A) 5 B) 6 C) 8 D) 1
-
The loop
while (*p) p++;stops when:A) p is NULL B) *p is '\0' C) p reaches 100 D) Never
-
Which is an error?
A)
char *p = "A"; p = "B";B)char a[] = "A"; a = "B";C)char a[] = "A"; a[0] = 'B';D) None
Show answers
- B: the array.
- B: e.
- C: 8.
- B: *p is '\0'.
- B: an array can't be assigned.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| char s[] = "Hi" | Editable array, sizeof = 3 |
|---|---|
| char *p = "Hi" | Points to read-only literal, sizeof = 8 |
| Modify literal | Undefined behaviour (crash) |
| Walk string | while (*p) p++; |
| Length | end − start |
| Copy idiom | while ((*d++ = *s++)); |
Frequently asked questions
- What is the difference between char array and char pointer?
- A char array owns editable memory; a char pointer only stores an address, often of a read-only literal, but can be re-pointed.
- Why does char *s = "abc"; s[0] = 'x'; crash?
- String literals live in read-only memory; writing to them is undefined behaviour.
- How do you find string length using a pointer?
- Move a pointer until '\0' and return end − start.
Remember
- Array = your photocopy; pointer to literal = notice board.
- Want to edit? Copy into an array.
Next Topic
Next lesson: Pointers and Functions in C. You will pass pointers to functions, return pointers safely and avoid returning local addresses.