Search code examples
cgarbagekernighan-and-ritchie

K&R Exercise 3-2 garbage characters


I am working through the K&R 2nd Edition and have run into a curious problem with exercise 3-2. For some reason only the \n shows up like it's supposed to and of the two tabs in my original string, one shows up as \ while the other is missing completely. I also get varying amounts of garbage in the string, the most current output string being "I \ am (micro symbol mu) . \n". Even more curious is there are a couple more spaces between the \n and period than in the original. I looked up the solution (https://code.google.com/p/k-and-r-exercises/source/browse/3-2.c) and it is fairly similar to what I did. Furthermore, I did two putchars in main, '\' and 't', and got the \t to display without issue. I am pretty stumped on what is causing this error and could really use your advice.

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

void    switchFunction(char s[], char t[]);

main(){

    char    originalString[] = "I \t am \t . \n \0";
    char    copiedString[1000];
    char    a, b;

    switchFunction(originalString, copiedString);
    printf(originalString);
    printf("\n");
    printf(copiedString);
    printf("\n");

    a = '\\';
    b = 't';
    putchar(a);
    putchar(b);

}

void switchFunction(char s[], char t[]){

    int i;
    int j = 0;
    int originalStringLen;

    originalStringLen = strlen(s);
    printf("Original is %d characters.\n", originalStringLen);

    for(i = 0; i < originalStringLen; ++i){
        switch(s[i]){
            case '\n':
                t[j] = '\\';
                j++;
                t[j] = 'n';
                j++;
                break;
            case '\t':
                t[j] = '\\';
                j++;
                t[j] = 't';
                j++;
                break;
            default:
                t[i] = s[i];
                j++;
        } 
    }       
    t[j] = '\0';
}

P.S. I did a putchar for every character in the new string inside the function (as they were getting assigned) and got significantly more garbage characters although the \t's show up without issue.


Solution

  • This is the problem line:

                t[i] = s[i];
    

    you need:

                t[j] = s[i];