Saturday 15 August 2015

c - String manupulation by adding spaces (' ') upto length 20 -



c - String manupulation by adding spaces (' ') upto length 20 -

i have function written in avr gcc atmega128 add together spaces string if length of string less 20 display in lcd. when don't utilize function continuously output expected when utilize continuously , display output, lastly string displayed. causes kind of problem ?

void parse(uint8_t* str, uint8_t endlen, uint8_t charac) { //str string passed, charac fill character, endlen length of string passed uint8_t len = 0; // length count start 0 while(str[len] != '\0') { len++; } while(len < endlen){ str[len] = charac; len++; } str[endlen] = '\0'; }

when phone call programme as

int main(void){ uint8_t str1[20] = "0123456789"; uint8_t str2[20] = "abcdefghij0123456789"; parse(str1, 20, ' '); fprintf(stderr, "%s", str1); parse(str2, 20, ' '); fprintf(stderr, "%s", str2); while(1); }

output :

0123456789

abcdefghij0123456789

but when phone call function as

int main(void){ uint8_t str1[20] = "0123456789"; uint8_t str2[20] = "abcdefghij0123456789"; parse(str1, 20, ' '); parse(str2, 20, ' '); fprintf(stderr, "%s", str1); fprintf(stderr, "%s", str2); while(1); }

output is:

abcdefghij0123456789

you write '\0' element 20 (that not exist) of string. undefined behavior.

c string

No comments:

Post a Comment