As said in the title, the goal is to copy a C-style string into memory without using any standard library functions or subscripting.
Here is what I have so far [SOLVED]
#include "std_lib_facilities.h"
char* strdup(const char* p)
{
int count = 0;
while (p[count]) ++count;
char* q = new char[count+1];
for (int i = 0; i < count + 1; ++i) *(q + i) = *(p + i);
}
int main()
{
char word[] = "Happy";
char* heap_str = strdup(word);
}
Obviously the problem is that allocating just *p (which is equivalent to p[0]) only allocates the letter "H" to memory. I’m not sure how to go about allocating the C-style string without subscripting or STL functions.
C-style string ends with ‘\0’. You need to traverse the string inside the function character by character until you encounter ‘\0’ to know how long it is. (This is effectively what you would do by calling strlen() to work it out.) Once you know how long the string is, you can allocate the right amount of memory, which is the length+1 (because of the ‘\0’).
To access the i’th element of an array p, one use subscript:
p[i].Subscript of the form
p[i]is formally defined to be*((p)+(i))by both the C standard (6.5.2.1 of C99) and the C++ standard (5.2.1 of C99). Here, one ofporiis of the type pointer to T, and the other is of integral type (or enumeration in C++). Because array name is converted automatically (in most types of use anyway) to a pointer to the first element of said array,p[i]is thus the i’th element of array p.And just like basic arithmetic,
((p)+(i))is equivalent to((i)+(p))in pointer arithmetic. This mean*((p)+(i))is equivalent to*((i)+(p)). Which also meanp[i]is equivalent toi[p].