Saturday, 15 February 2014

c - K&R Exercise 3-2 garbage characters -



c - K&R Exercise 3-2 garbage characters -

i working through k&r 2nd edition , have run curious problem exercise 3-2. reason \n shows it's supposed , of 2 tabs in original string, 1 shows \ while other missing completely. varying amounts of garbage in string, current output string beingness "i \ (micro symbol mu) . \n". more curious there couple more spaces between \n , period in original. looked solution (https://code.google.com/p/k-and-r-exercises/source/browse/3-2.c) , similar did. furthermore, did 2 putchars in main, '\' , 't', , got \t display without issue. pretty stumped on causing error , utilize advice.

#include<stdio.h> #include<string.h> void switchfunction(char s[], char t[]); main(){ char originalstring[] = "i \t \t . \n \0"; char copiedstring[1000]; char a, b; switchfunction(originalstring, copiedstring); printf(originalstring); printf("\n"); printf(copiedstring); printf("\n"); = '\\'; b = 't'; putchar(a); putchar(b); } void switchfunction(char s[], char t[]){ int i; int j = 0; int originalstringlen; originalstringlen = strlen(s); printf("original %d characters.\n", originalstringlen); for(i = 0; < 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. did putchar every character in new string within function (as getting assigned) , got more garbage characters although \t's show without issue.

this problem line:

t[i] = s[i];

you need:

t[j] = s[i];

c garbage kernighan-and-ritchie

No comments:

Post a Comment