Home > Back-end >  Implementing strdup() in c exercise from Bjarne's Book, copying char* to another char* then p
Implementing strdup() in c exercise from Bjarne's Book, copying char* to another char* then p

Time:03-01

I'm learning c using the book:Programming Principles and Practice using C by Bjarne Stroustrup.
In Chapter 19, exercise 1
implement strdup() functions which will copy a c strings into another using only de-referencing method (not subscripting).
My copying doesn't print anything I've been look for answers for days.
Please anyone can help me?
Below is the entire code:-

#include <iostream>
using namespace std;

char* strdup(const char* q) {
    // count the size
    int n {0};
    while(q[n]) {
          n;
    }
    // allocate memory
    char* p = new char[n 1];
    
    // copy q into p
    while(*q) {
        *p   = *q  ;
    }
    // terminator at the end
    p[n] = 0;
    return p;
}


int main()
{
    const char* p = "welcome";
    cout << "p:" << p << endl;

    const char* q = strdup(p);
    cout << "q:" << q << endl;
    
    // check to see if q get new address
    cout << "&p:" << &p << endl;
    cout << "&q:" << &q << endl;
    
    return 0;
}

CodePudding user response:

using only de-referencing method (not subscripting)

So this is already wrong, because is uses the subscript operator []:

    // count the size
    int n {0};
    while(q[n]) {
          n;
    }

I just don't know how to turn the pointer back to the first char.

Well, there are two basic approaches:

  1. stop damaging your original pointer in the first place. You can introduce new variables, remember?

    char* p_begin = new char[n 1];
    char* p_end = p_begin   n   1; // copy the terminator too
    for (char *tmp = p_begin; tmp != p_end; *tmp   = *q  ) ;
    return p_begin;
    
  2. you know exactly how far to move p to get back to the original value, because you already calculated how long the string is!

    while(*q) {
        *p   = *q  ;
    }
    *p = 0; // you already moved p and aren't supposed to be subscripting anyway
    return p - n;
    

Finally, you can get the size without subscripting using exactly the same technique: either you use a temporary variable to find the terminator, or if you advance q as you go, then subtract n from it again at the end.

Oh, and if you're having trouble visualizing the values of all your variables - learn to use a debugger (or just add lots of print statements). You need to understand how your state changes over time, and watching it is much more helpful than just observing the result of a black box and trying to guess what happened inside.

CodePudding user response:

Replace this:

while(*q) {
    *p   = *q  ;
}

..with this:

for (int i = 0; i < n; i  ) {
    p[i] = q[i];
}

Problem solved.

  • Related