Skip to content
StudyFame

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 *p and p++.
  • 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 */
Pointchar arr[] = "Hello"char *ptr = "Hello"
StorageOwn array (stack)Literal in read-only memory + a pointer
Change a letterYesNo (crash risk)
Point to another stringNo (use strcpy)Yes: ptr = "Bye";
sizeof68 (pointer size)
arr++ / ptr++ErrorAllowed

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

  1. char *p = city; makes p point to the first character.
  2. *p is the current character. The loop runs until it reaches '\0'. Since '\0' is 0 (false), while (*p) means the same thing.
  3. p++ moves to the next character (1 byte, since char is 1 byte).
  4. p - city is pointer subtraction: how far p moved, which equals the length.
  5. printf("%s", p) prints from wherever p points up to '\0', so city + 3 prints "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')
    ;
  1. *src++ reads the current source character, then moves src.
  2. *dest++ = ... stores it at dest, then moves dest.
  3. 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_length uses 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 | 32 turns a capital letter into small (it sets the bit worth 32). It's a common trick; tolower from 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

MistakeWhat happensFix
char *s = "abc"; s[0] = 'x';Crash (segmentation fault)char s[] = "abc";
char *s; scanf("%s", s);Writes to a random addresschar s[50]; or malloc first
strcpy(p, "Hi") where p points to a literalCrashCopy into an array
Losing the start after p++Can't print the whole string againUse a second pointer to walk
if (p == "yes")Compares addressesstrcmp(p, "yes") == 0

Pointers and Strings Practice Questions

  1. What is the difference between char s[] = "C" and char *s = "C"?
  2. Why does changing a character of a string literal crash?
  3. What does printf("%s", s + 2) print if s holds "Kolkata"?
  4. Write a loop that moves a pointer p to the end of a string.
  5. Why do string function parameters use const char *?
Show answers
  1. The first is an editable 2-byte array; the second is a pointer to a read-only literal (sizeof 8 on 64-bit).
  2. String literals are stored in read-only memory; writing there is undefined behaviour.
  3. "lkata".
  4. while (*p) p++;
  5. 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)

  1. Which can be modified safely?

    A) char *s = "abc";   B) char s[] = "abc";   C) Both   D) Neither

  2. char *p = "Delhi"; printf("%c", *(p + 1)); prints:

    A) D   B) e   C) l   D) elhi

  3. sizeof(p) for char *p = "Hello"; on 64-bit:

    A) 5   B) 6   C) 8   D) 1

  4. The loop while (*p) p++; stops when:

    A) p is NULL   B) *p is '\0'   C) p reaches 100   D) Never

  5. 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
  1. B: the array.
  2. B: e.
  3. C: 8.
  4. B: *p is '\0'.
  5. 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 literalUndefined behaviour (crash)
Walk stringwhile (*p) p++;
Lengthend − start
Copy idiomwhile ((*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.