michaelmeyer
michaelmeyer

Reputation: 8205

Concatenating two string (K&R)

I'm trying to mimic a sample program given in K&R, which looks like this:

void strcat(char s[], char t[])
{
    int i, j;
    i = j = 0;
    while (s[i] != '\0') /* find end of s */
        i++;
    while ((s[i++] = t[j++]) != '\0') /* copy t */
        ;
}

I want to do the same thing, except that, instead of appening t to s, I'd like to copy both into a new string. My try is as follows :

#include <stdio.h>
#include <string.h>

void concat
(const char lstr[], const char rstr[], char outstr[])
{
    int i, j;

    i = j = 0;
    while (lstr[i] != '\0')
        outstr[i++] = lstr[i++];
    while ((outstr[i++] = rstr[j++]) != '\0')
        ;
}

int main(void)
{
    char lword[] = "foo";
    char rword[] = "bar";
    char outword[strlen(lword) + strlen(rword)];

    concat(lword, rword, outword);
    printf("%s\n", outword);
}

However, the above only prints garbage (I mean f�����bar). I can't find out where the error lies.

Upvotes: 0

Views: 164

Answers (3)

hmjd
hmjd

Reputation: 121981

Two problems:

  • No space for terminating null character in outword. Needs to be:

    char outword[strlen(lword) + strlen(rword) + 1];
                                             /*^^^*/
    
  • This is undefined behaviour as i is being modified twice in the same statement:

    outstr[i++] = lstr[i++];
    
    /* Change to: */
    
    while (lstr[i] != '\0')
    {
        outstr[i] = lstr[i];
        ++i;
    }
    

With these two changes the program produces a new concatenated string (http://ideone.com/9QbU0q).

Upvotes: 3

Chris Ryding
Chris Ryding

Reputation: 1533

When copying lstr to outstr you're incrementing your index twice. Use outstr[i] = lstr[i++]

Upvotes: -1

Mark Ransom
Mark Ransom

Reputation: 308266

Every string in C needs to end with a null character, which won't be visible. It does however need to be accounted for in the size of the memory you allocate.

Upvotes: 3

Related Questions