c - K&R - section 1.9: understanding character arrays (and incidentally buffers) -
let's start basic question character arrays not understand description in book:
- does every character array end '\0'?
- is length of equal number of characters + 1 '\0'?
- meaning if specify character array length of 10 able store 9 characters not '\0'?
- or '\0' come after last array slot, 10 slots used character , 11th non-reachable slot contain '\0' char?
going further example in section, defines getline() function reads string , counts number of characters in it. you can see entire code here (in example getline() changed gline(), since getline() defined in newer stdio.h libraries)
here's function:
int getline(char s[], int lim) { int c, i; (i = 0; < lim - 1 && (c = getchar()) != eof && c != '\n'; ++i) { s[i] = c; } if (c == '\n') { s[i] = c; ++i; } s[i] = '\0'; return i; }
it explained array stores input in manner:
[h][e][l][l][o][\n][\0]
, function return count of 6, including '\n' char, true if loop exits because of '\n' char.
if loop exits because has reached it's limit, return array (as understand this): [s][n][a][z][z][y][\0]
count 6.
comparing both strings return they're equal when "snazzy" longer word "hello", , code has bug (by personal requirements, not count '\n' part of string).
trying fix tried (among many other things) remove adding '\n' char array , not incrementing counter, , found out incidentally when entering more characters array store, characters wait in input buffer, , later passed getline() function, if enter:
"snazzy lolz\n"
use this:
first getline() call: [s][n][a][z][z][y][\0]
second getline() call: [ ][l][o][l][z][\n][\0]
this change introduced interesting bug, if try enter string 7 characters long (including '\n') program quit straight away because pass '\0' char next getline() call return 0 , exit while loop calls getline() in main().
i confused next. how can make not count '\n' char avoid bug created?
many thanks
there convention in c strings end null character. on convention, questions based. so
- does every character array end '\0'?
no, ends \0 because programmers put there.
- is length of equal number of characters + 1 '\0'?
yes, because of convention. thereto, example allocate 1 more byte (char) length of string accommodate \0.
strings stored in character arrays such char s[32];
or char *s = malloc(strlen(name) + 1);
Comments
Post a Comment