我错过了一些非常简单的东西吗?因为我似乎找不到我的代码没有动态存储字符串的原因。当我最后打印它们时,我得到的只是空白行。它应该打印任意行数的最后“n”行。不过,实际行的存储似乎存在问题。任何人都可以伸出援助之手吗?
顺便说一句,这不是硬件。这是 K&R 书中的一个问题(其答案在线)。我正在尝试自己学习C。
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 to %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';
}