
-----------------------------------
abcdefghijklmnopqrstuvwxy
Mon Jul 30, 2007 8:30 pm

operator overloading
-----------------------------------
What's wrong with this?


#include 

char* operator+(char* one, char* two) {
  strcat(one, two);
  return one;
}

int main() {
  char* one = "You";
  char* two = "Suck";
  printf(one+two);
}


-----------------------------------
rizzix
Tue Jul 31, 2007 1:11 am

RE:operator overloading
-----------------------------------
C does not have operator overloading. I think you're mixing up C with C++.

-----------------------------------
abcdefghijklmnopqrstuvwxy
Tue Jul 31, 2007 2:31 am

RE:operator overloading
-----------------------------------
So what is the easiest way to join two strings without declaring a new variable to hold them?  

To me it seems onerous to declare a new variable and use strncat()...

-----------------------------------
md
Tue Jul 31, 2007 9:25 am

RE:operator overloading
-----------------------------------
strcat( string1, string2); just like in your code. However, if you do this with your code you'll get a nice overflow.

C is horrible for strings, they end up just being glorified arrays that use a null character to mark the end. If you use strcat() and the resulting string is longer then the array you are attepting to store it in C really has no way of knowing, so it does as you ask. Which of course leads to all sorts of messy errors.

Creating a new string is unfortunately almost always the only way to be sure that you don't write beyond the length of your original strings.

-----------------------------------
wtd
Tue Jul 31, 2007 3:13 pm

RE:operator overloading
-----------------------------------
The best route is to use a function which allocates and returns a new string.  However, beware!  If you do this, you will be tempted to use it immediately without assigning the result of that function to a variable.

This way lies madness, as every time you use the function, you allocate memory which must be freed, and without doing so, you have a memory leak.  :)

-----------------------------------
OneOffDriveByPoster
Tue Aug 07, 2007 5:31 pm

Re: RE:operator overloading
-----------------------------------
If you do this, you will be tempted to use it immediately without assigning the result of that function to a variable.
wtd, of course you know this, but for the benefit of those who don't:
extern void my_malloc_strcat(char **, char const *, char const *);

