Define a C-string function

void append(const char * v, const char * w, char * buffer)

that appends the characters of C-string w to the characters of C-string v and stores the result in buffer. (Don't forget the terminating null character .)

You can assume that the function is called with a buffer whose size is at least the sum of the sizes of v and w.
Use pointer notation. No square brackets allowed.

Here is my solution:

void append(const char *v, const char  *w, char *buffer)
    const char *p = v;
    while(*p != '\0')
    while(*w != '\0')
        *p++ += *w++;
    *buffer = *p;
    p = '\0';

Right now, all I am getting is the error message: assignment of read-only location. This is occurring in this line: *p++ += *w++. Is there anything that I need to do to fix this error and get the correct solution?

Your error is that the function you've written is illogical. It looks like you wrote the first thing that came to mind and somehow hoped that it would magically solve the problem.

Can you write the code that will copy the 'v' string to the buffer?
Get that part working to start with and then the rest should be simple.

Try using strcpy() and strcat() instead, as in:

if (buffer != 0) // test for a null buffer pointer.
    ::strcpy(buffer, w);
    ::strcat(buffer, v);

Yes, these are C functions, but they work just fine with C++ and are appropriate as your function arguments are simply char* and not std::string& or std::string* objects.

Edited 2 Years Ago by rubberman

This article has been dead for over six months. Start a new discussion instead.