Well, since this a self-teaching excercise, here's an alternative look at a solution that can be compared/contrasted with KTC's nice explanation of the equivalence between subscripting and pointer arithmetic.
The problem appears to be, "implement a strdup() function without using standard library facilities or subscripting".
I'm going to make an exception for malloc()
, as there's no reasonable way to do the above without it, and I think that using it isn't detrimental to what's being taught.
First, let's do a basic implementation of strdup(), calling functions that are similar to the ones we might use from the library:
size_t myStrlen( char* s);
char* myStrcpy( char* dst, char* src);
char* strdup( char* p)
{
size_t len = myStrlen( p);
char* dup = (char*) malloc( len + 1); /* include space for the termination character */
if (dup) {
myStrcpy( dup, p);
}
return dup;
}
Now lets implement the worker functions without subscripting:
size_t myStrlen( char* s)
{
size_t len = 0;
while (*s != '\0') { /* when s points to a '\0' character, we're at the end of the string */
len += 1;
s += 1; /* move the pointer to the next character */
}
return len;
}
char* myStrcpy( char* dst, char* src)
{
while (*src != '\0') { /* when src points to a '\0' character, we're at the end of the string */
*dst = *src;
++dst; /* move both pointers to next character location */
++src;
}
*dst = '\0'; /* make sure the destination string is properly terminated */
return dst; /* this is just done to make myStrcpy() closely mimic strcpy() */
}
And there you have it. I think this satisfies the condition of the assignment and shows how pointers can be manipulated to move though an array of data items instead of using subscripting. Of course, the logic for the myStrlen()
and myStrcpy()
routines can be moved inline if desired, and more idiomatic expressions where the pointer increment can happen in the expression that copies the data can be used (but I think that's more confusing for beginners).