简体   繁体   中英

implementation Strcat Function

I've got a programming question about the implementation of strcat() function. I have been trying to solve that problem and I got some Access violation error.

My created function:

char str_cat(char str1, char str2)
{
    return str1-'\0'+str2;
}

what is wrong in the above code?

One more question please, is "iostream" a header file? where can I get it?

thanks

Nothing is right in the above code.

  • You need to take char * parameters
  • You need to return a char * if you have to return something (which isn't needed)
  • You'll need to loop over the string copying individual characters - no easy solution with + and -
  • You'll need to 0-terminate the result

Eg like this:

void strcat(char * Dest, char const * Src) {
  char * d = Dest;
  while (*d++);
  char const * s = Src;
  while (*s) { *d++ = *s++; }
  *d = 0;
}

Why do you need to do this? There's a perfectly good strcat in the standard library, and there's a perfectly good std::string which you can use + on.

Unfortunately, everything is wrong with this function, even the return type and argument types. It should look like

char * strcat(const char *str1, const char *str2)

and it should work by allocating a new block of memory large enough to hold the concatenated strings using either malloc (for C) or new (for C++), then copy both strings into it. I think you've got your (home)work cut out for you, though, as I don't think you know much of what any of that means.

Don't want to sound negative but there is not much right with this code.

Firstly, strings in C are char*, not char.

Second, there is no way to 'add' or 'subtract' them the way you would hope (which is sort of kind of possible in, say, python).

iostream is the standard I/O header for C++, it should be bundled with your distribution.

I would really suggest a tutorial on pointers to get you going - this I found just by googling "ansi c pointers" - I'm guessing the problem asks you for a C answer as opposed to C++, since in C++ you would use std::string and the overloaded operator+.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM