Pointer Arithmetic With Strings
Extend your knowledge about pointer arithmetic using strings.
We'll cover the following...
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";
strpoints to the first element inside the string. It’s the character'a'.str + 1points to the second element inside the string. It’s the character'b'.str + 2points to the first element inside the string. It’s the character'c'.str + 3points to the third element inside the string. It’s the character'd'.
We can use array notation and instead of str + i, use str[i].
In the following code:
- On line 8, we print the first character using the pointer and array notation.
- On lines 11–14, we iterate over the string character by character. We use the array notation for it.
- On lines 17–24, we iterate over the string character by character. We use the pointer notation for it.
startAddrpoints to the beginning of the string and increments to move to the right, character by character.endAddris the address at the end of the array.- We keep printing until we reach the end address and then stop.
- To calculate the index of the character (0, 1, 2, …), we subtract the
startAddrfromstr. We get the offset between the two addresses. - To read the character at the current address, we dereference the
startAddrpointer.