Hi all,
I'm having some trouble with my program, I know my copy and my clone function is correct, basically I just need to create the functions to achieve the desired result.
Here is my code so far
#include <stdio.h>
#include <stdlib.h>
// helpers
size_t length(const char *s)
{
size_t l = 0;
if (s) {
while (*s++) {
++l;
}
}
return l;
}
char* copy(char *d, const char *s)
{
char *p = d;
if (s) {
while (*s) {
*p++ = *s++;
}
}
*p = 0;
return d;
}
char* clone(const char *s)
{
if (s) {
char *p = (char*)malloc(length(s) + 1);
return copy (p, s);
}
return NULL;
}
// str
struct str {
private:
char *p;
public:
str();
string p;
str(const char *s);
str(int n, const char *s);
~str();
};
str::str()
: p(NULL)
{}
str::str(const char *s)
{
p = clone(s);
}
str::str(int n, const char *s)
{
size_t l = length(s);
p = (char*)malloc(l * n + 1);
for (int i = 0; i < n; ++i) {
copy(p + i * l, s);
}
}
str::~str()
{
if (p) {
free(p);
}
}
size_t str::size()
{
return ::length(p);
}
/*
Expected program output:
(empty)
Hello World!
Hello!Hello!Hello!
HHHHH
*/
void main()
{
str s0;
s0.print();
// s0.append("Hello");
// s0.append(" ");
// s0.append("World!");
// s0.print();
// str s1(3, "Hello!");
// s1.print();
// str s2(5, 'H');
// s2.print();
}
I know in the structure I could do something in C++ like
append(string name)
{
p += name;
}
size_t size();
print(string name)
{
printf("%s \n" , &s);
}
but i'm pretty sure thats incorrect.
Any help would be appreciated, thanks!