Open In App

Pointer Arithmetic with Strings

Last Updated : 11 Jun, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Pointer Arithmetic is a technique in C that allows manipulation of memory addresses. We can also manipulate arrays using pointer arithmetic as the arrays are nothing but contiguous memory block.

Strings are also character arrays which are arrays of characters terminated by a null character ('\0'), so pointer arithmetic becomes an efficient tool to traverse, search, and manipulate the characters directly through their memory locations.

We can do all the pointer arithmetic operations with strings except assignment to NULL.

  • Increment/Decrement a Pointer.
  • Addition/Subtraction of Integer to/from a Pointer.
  • Comparison of Pointers in a String.
  • Pointer Traversal in Strings.

Let's see how the pointer arithmetic helps in simplifying different operations in C strings.

1. String Comparision

C
#include <stdio.h>

// Compare two strings using pointers
int compare(char *s1, char *s2) {
    while (*s1 && (*s1++ == *s2++));
    return *s1 - *s2;
}

int main() {
    char s1[] = "Geeks";
    char s2[] = "Geeksfor";
    
    if (compare(s1, s2) == 0)
        printf("Strings are same");
    else
        printf("Strings are not same");
    return 0;
}

Output
Strings are not same

As we can see, No index variable needed. Faster, shorter, and cleaner code.

2. String Copying

C
#include <stdio.h>

void copy(char dest[], char src[]) {
    while (*dest++ = *src++ );
}

int main() {
    char src[] = "Geeks";
    char dest[20];
    
    copy(dest, src);
    printf("%s", dest);
    return 0;
}

Output
Geeks

Using pointers, we do direct element assignment via pointers.

3. String Length Calculation

C++
#include <stdio.h>

// Calculate string length using pointer
// arithmetic
int length(char *str) {
    char *p = str;
    while (*p++);
    return p - str - 1;
}

int main() {
	char s1[] = "Geeks";
	printf("%d", length(s1));
	return 0;
}

4. String Concatenation

C
#include <stdio.h>

// Concatenate src to dest using pointer arithmetic
void concatenate(char *dest, char *src) {
    
    // Move dest pointer to end of string
    while (*dest++);

    // Copy src to end of dest
    while (*dest++ = *src++) {
    }
}


int main() {
	char s1[50] = "Geeks";
	char s2[] = "forGeeks";
	concatenate(s1,s2);
	printf("%s", s1);
	
	return 0;
}

Output
Geeks

As we can see, working with strings get simpler and concise by using pointers and pointers arithmetic. This behaviour is not outside the normal behaviour of the strings as the strings in the end are just block of memory.


Next Article
Article Tags :

Similar Reads