C : Dynamically storing strings (of dynamic sizes!)? -
am missing incredibly simple? because can't seem find reason why code isn't storing strings dynamically. blank lines when print them @ end. supposed print last "n" lines of arbitrary number of lines. there seems problem storage of actual lines though. can lend hand?
this not hw way. problem k&r book (whose answers online). i'm trying learn c on own.
void tail5_13(int n) { int maxpoint = 3; size_t *maxlength; *maxlength = sizeof(char) * 10; char **pointptr = malloc(sizeof(void *) * maxpoint); char **pointcnt = pointptr; char *lineptr = malloc(sizeof(char) * *maxlength); int numlines = 0; int printnum = 0; int c; while((c = getline(&lineptr, maxlength, stdin)) > 1) { if(numlines < maxpoint) { storeline5_13(pointcnt, lineptr, c); pointcnt++; } else { maxpoint *= 2; printf("increased pointer amount %d\n", maxpoint); pointptr = (char **) realloc(pointptr, sizeof(void *) * maxpoint); storeline5_13(pointcnt, lineptr, c); pointcnt++; } numlines++; } if(n <= numlines) printnum = n; else printnum = numlines; while(printnum-- > 0 ) { printf("%s\n", *(pointcnt-1)); } } void storeline5_13(char** pointcnt, char* line, int length) { *pointcnt = (char *) malloc(sizeof(char) * length); while(*line != '\n') { *((*pointcnt)++) = *line++; } **pointcnt = '\0'; }
size_t *maxlength; *maxlength = sizeof(char) * 10;
you're dereferencing wild (unassigned) pointer.
instead, should be:
size_t maxlength = sizeof(char) * 10; // ... char *lineptr = malloc(sizeof(char) * maxlength); // ... while((c = getline(&lineptr, &maxlength, stdin)) > 1)
then, you're using automatic variable.
Comments
Post a Comment