LearnFrenzy
Sign in Take a free test

Pointers and Dynamic Memory · Pointer Programs · Question 3

Length and copy of a C string with pointers in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

Write your own versions of strlen and strcpy using only pointer arithmetic, and use them on a word.

Solution
main.cpp
#include <iostream>

std::size_t my_strlen(const char* s) {
    const char* p = s;
    while (*p) ++p;            // stop at '\0'
    return static_cast<std::size_t>(p - s);
}

char* my_strcpy(char* dest, const char* src) {
    char* d = dest;
    while ((*d++ = *src++)) {} // copies the '\0' too
    return dest;
}

int main() {
    const char* word = "LearnFrenzy";
    char buffer[32];
    my_strcpy(buffer, word);
    buffer[0] = 'l';
    std::cout << my_strlen(word) << ' ' << buffer << ' ' << word << '\n';
    return 0;
}

Output Verified by compiling and running

11 learnFrenzy LearnFrenzy

The length is the distance between the start and the terminating '\0'. The copy loop assigns and advances both pointers in one expression and ends after copying the terminator.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links