Search⌘ K
AI Features

Pointer Arithmetic With Strings

Explore how pointer arithmetic operates specifically with strings in C. Understand the mechanics of navigating characters using pointers and array notation, learn about the null terminator's role, and how to safely iterate through strings while managing memory effectively.

We'll cover the following...

Introduction

Pointer arithmetic with strings works the same as pointer arithmetic with other array types.

However, keeping in mind that the size of char is 1 byte, we can simply apply the pointer arithmetic rules.

For char *ptr;, ptr + 5 will add 5 * sizeof(char), which is equal to 5. Then, we can omit thinking about the size of the data type and doing multiplication because the size is 1.

If we had an int pointer, ptr + 5 will add 5 * sizeof(int) = 5 * 4 = 20. We have to do one more multiplication step, which we can omit for char arrays.

Pointer arithmetic example

Consider the following example:

char* str = "abcd";
  • str points to the first element inside the string. It’s the character 'a'
...