A peculiar bug while reading and printing strings of *char in C -
i've encountered odd. string of char (let's call word
) turns out have additional letters when print it.
contatenated letter varies depending on:
- the length of proper prefix word.
- the number of spaces after word.
i'm parsing word
line
1 line form standard input. i'm using function readword
word
out of line
:
void readword(char **linepointer, char **wordpointer){ char *line = *linepointer; char *word = *wordpointer; while (!isendofline(line) && islowercaseletter(*line)){ *word = *line; word++; line++; } word++; *word = '\0'; printf("the retrieved word is: %s.\n", *wordpointer) *linepointer = line; }
my inputs/outputs (please note call readword
function after taking care of insert
, whitespace between):
// input 1 : insert foo insert ba // several spaces after 'ba' // output 2: retrieved word foo. retrieved word bas. // input 1 : insert foo insert ba // several spaces after 'bar' // output 2: retrieved word foo. retrieved word bare.
i thinking whether allocate *word
, guess do:
root.word = (char *)malloc(sizeof(char *)); //root structure
moreover, unlikely connected errors of reassigning word
string because clear @ beginning of readword()
function.
thank help. indeed challenging bug me , don't know else can do.
update
it turns out have problems allocating/reassigning, since:
//input insert foo//no spaces insert bar //spaces here //output word variable before calling readword function: ' '. retrieved word foo. word variable before calling readword function: 'insert foo '. retrieved word bare.
never trust input, check spaces go beginning of word.
you increment word 1 many, @rpattiso notes.
i have doubts memory allocation (you don't show code): root.word = (char *)malloc(sizeof(char *));
allocates room pointer char, not allocate room characters themselves. readword can that.
the following adapted version should work (updated):
void readword(char **linepointer, char **wordpointer){ char *line = *linepointer; int i; while (!isendofline(line) && !islowercaseletter(*line)) line++; // go begin of word *linepointer= line; while (!isendofline(line) && islowercaseletter(*line)) line++; // go end of word i= line - *linepointer; // allocate room word , copy *wordpointer= malloc((i+1) * sizeof(char)); strncpy(*wordpointer, *linepointer, i); (*wordpointer)[i]= '\0; printf("the retrieved word is: %s.\n", *wordpointer); *linepointer = line; }
Comments
Post a Comment