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!

Ancient Dragon commented: Thanks for taking the time to use code tags on your first post :) +36
VernonDozier commented: More positive rep for first-post code tags. +16

lines 37-80: That is c++ code, not C. Are you writing a C program (afterall this is the C forum) or a c++ program ?

It's really strange, my instructor teaches us in C for the most part but incorporates C++ elements here and there

Then I guess you are taking a c++ class. I'm moving this to the c++ board.

>>p += name;

No, it doesn't work that way because p is a pointer, not a std::string object. And I would suggest you replace malloc() with new and free() with delete or delete[] because this is a c++ program. But if your teacher insists on using malloc() then change the code I have posted below accordingly.

if( p != NULL)
{
   char* p1 = new char[strlen(name)+strlen(p)+1);
   strcpy(p1,p);
   strcat(p1,name);
    delete[] p;
   p = p1;
}
else
{
    p = new char[strlen(name)+1];
    strcpy(p, name);
}

>>p += name;

No, it doesn't work that way because p is a pointer, not a std::string object. And I would suggest you replace malloc() with new and free() with delete or delete[] because this is a c++ program. But if your teacher insists on using malloc() then change the code I have posted below accordingly.

if( p != NULL)
{
   char* p1 = new char[strlen(name)+strlen(p)+1);
   strcpy(p1,p);
   strcat(p1,name);
    delete[] p;
   p = p1;
}
else
{
    p = new char[strlen(name)+1];
    strcpy(p, name);
}

Thanks for your reply, we actually haven't covered strcpy and strcat yet. After doing some research online I think something like this is closer to what he wanted

/* appends one string to another */
             while(*dest != '\0')
             {
                     *dest++;
             }
	while (*src != '\0')
		*dest++ = *src++;

	*dest = '\0';

Do you think thats closer to the right track?

Something like that.

char* p1 = (char *)malloc(strlen(name)+strlen(p)+1));
char* p2 = p1;
char p3 = p;
while(*p3)
   *p2++ = *p3++;
p3 = name;
while( *p3 )
   *p2++ = *p3++;
*p2 = 0;
free(p);
p = p2;

@Ancient Dragon

*p2 = 0;

Hey shouldn't the above code be

*p2 = '\0';

more precisely to signify null character even though both lead to ascii zero itself.

And you normally avoid typecasting of malloc right ? Any special purpose here ?

0 is the same as '\0' -- use which ever one you want. I just find 0 easier to type :)

typecasting is required in c++, but not in C. Since this is c++ board the typecast would be required.

Thanks again for your replies.

This might sound strange but we've never used strlen (and i'm pretty sure we're not supposed to either). Do I just call the first function instead?

size_t length(const char *s)
{
       size_t l = 0;
       if (s) {
               while (*s++) {
                       ++l;
               }
       }
       return l;
}

Back to real OP problems ;)

Evidently struct str definition is not complete (moreover: it's incorrect). Where are print and append member functions? Why string p member? Where are copy constructor and operator= (both are obligatory for classes with pointers to dynamically allocated data chunks). Why malloc/free C-function calls instead of standard C++ new/delete operators? What for these precious i*1 terms?..

The print and append functions I still need to make, the print one is easy but it's the append one I'm having some trouble with

0 is the same as '\0' -- use which ever one you want. I just find 0 easier to type :)

Except that the compiler sometimes will bitchslap me, with errors or warnings, if I use zero instead of a '\0'.

Well not with pointers, but with other things that out of habit I use a plain zero on, instead of what it's supposedly expecting.

Thanks again for all your help, i'm nearly there. I'm having a little trouble recognizing if the function is empty. One of our assignments is to have it say 'empty' if it is in the print function, i thought it would be something like

void print()
       {
		  if(printf("%s \n" , p) == 'NULL')
			  printf("(empty)\n");
		  else
		  printf("%s \n" , p);
			   
       }

but it doesn't seem to be the case. Any ideas?

The function can't be empty ;)
Probably you want

void str::print() const
{
    if (p)
        printf("%s\n",p);
    else
        printf("(empty)\n");
}

Why printf in C++ code?

>any ideas?
Hmm, may be re-read textbooks...

Thanks for your help!

Honestly i'm not too sure, it's supposed to be a C class but for whatever reason our instructor uses C++ here and there.

Honestly i'm not too sure, it's supposed to be a C class but for whatever reason our instructor uses C++ here and there.

Alas, no such animals as classes (or structures with constructors, see OP) in C ;)
Probably your instructor is a far...far-sighted person...
Well, the birthname of the C++ was C with Classes...

Alas, no such animals as classes (or structures with constructors, see OP) in C ;)
Probably your instructor is a far...far-sighted person...
Well, the birthname of the C++ was C with Classes...

His teaching style is definitely the most unorthodox I've ever seen.

Turns out there's one last thing before i'm done. I thought for the end part that has

str s2(5, 'H');
s2.print();

I could just change the 'H' to "H", but instead he wants us to create a constructor which I know will be

str::str(int n, char c)
{
}

I'm not too sure how to implement this though, thanks again for all your help guys.

Here's what I have in my constructor for my s2.print function so far

str::str(int n, char c) 
{
	  p = (char*)malloc(n + 1);
	  for (int  i = 0; i < n; ++i)
	   {
             copy(p + i * l, c);
       }


}

I'm not too sure if this is correct, but I'm getting this error
Error 1 error C2511: 'str::str(int,char)' : overloaded member function not found in 'str' and I'm not too sure what this means. Any ideas?

Evidently the str::str(int n, char c) constructor generates a string "ccc...c" n times. Assign c to p[i] in the loop and don't forget to assign terminating zero byte '\0' to p[n] element after that.

Declare this constructor as all other members in str definition (that's why C2511 error occured).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.