...

/

Pointer Arithmetic With Strings

Pointer Arithmetic With Strings

Extend your knowledge about pointer arithmetic using strings.

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'
...