求教指针运用问题。《c语言入门经典》第7章例题13题想了两天还是不明白
c语言入门经典(第4版)例题7.13题,红线的部分想了两天一直不明白以下为全部代码
/* Program 7.13 Generalizing string input */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const size_t BUFFER_LEN = 128; /* Length of input buffer */
const size_t NUM_P = 100; /* maximum number of strings */
int main(void)
{
char buffer[BUFFER_LEN]; /* Input buffer */
char *pS[NUM_P] = { NULL }; /* Array of string pointers */
char *pbuffer = buffer; /* Pointer to buffer */
int i = 0; /* Loop counter */
printf("\nYou can enter up to %u messages each up to %u characters.",
NUM_P, BUFFER_LEN-1);
for(i = 0 ; i<NUM_P ; i++)
{
pbuffer = buffer ; /* Set pointer to beginning of buffer */
printf("\nEnter %s message, or press Enter to end\n",
i>0? "another" : "a");
/* Read a string of up to BUFFER_LEN characters */
while((pbuffer - buffer < BUFFER_LEN-1) &&
((*pbuffer++ = getchar()) != '\n'));
/* check for empty line indicating end of input */
if((pbuffer - buffer) < 2)
break;
/* Check for string too long */
if((pbuffer - buffer) == BUFFER_LEN && *(pbuffer-1)!= '\n')
{
printf("String too long - maximum %d characters allowed.", BUFFER_LEN);
i--;
continue;
}
*(pbuffer - 1) = '\0'; /* Add terminator */
pS[i] = (char*)malloc(pbuffer-buffer); /* Get memory for string */
if(pS[i] == NULL)
{
printf("\nOut of memory - ending program.");
return 1;
}
/* Copy string from buffer to new memory */
strcpy(pS[i], buffer);
}
/* Output all the strings */
printf("\nIn reverse order, the strings you entered are:\n");
while(--i >= 0)
{
printf("\n%s", pS[i] ); /* Display strings last to first */
free(pS[i]); /* Release the memory we got */
pS[i] = NULL; /* Set pointer back to NULL for safety */
}
return 0;
}
问题如下:
1、请问这一段
if((pbuffer - buffer) == BUFFER_LEN && *(pbuffer-1)!= '\n')
{
printf("String too long - maximum %d characters allowed.", BUFFER_LEN);
i--;
continue;
}
*(pbuffer - 1) = '\0';
为什么判断pbuffer - buffer是否等于BUFFER_LEN,而不是BUFFER_LEN - 1?
while((pbuffer - buffer < BUFFER_LEN-1) && ((*pbuffer++ = getchar()) != '\n'));这个语句当pbuffer - buffer == BUFFER_LEN-1时已经结束while循环,那pbuffer - buffer又怎么可能会等于BUFFER_LEN。
2、while((pbuffer - buffer < BUFFER_LEN-1) && ((*pbuffer++ = getchar()) != '\n'));是否等价于
for(; ; )
{
*pbuffer++ = getchar();
if(*(pbuffer - 1) == '\n')
break;
if(pbuffer - buffer >= BUFFER_LEN-1)
break;
}
3、printf()那一句为什么最大字符数是BUFFER_LEN?字符数组字节长度都是包括了'\0'终止符的啊,最大长度应该是BUFFER_LEN - 1吧?前面的语句printf("\nYou can enter up to %u messages each up to %u characters.", NUM_P, BUFFER_LEN-1);不是说每个字符串最多BUFFER_LEN - 1的字符?
4、 *(pbuffer - 1) = '\0';这一语句,假充BUFFER_LEN = 5,NUM_P = 3,如果我输入abcd然后回车,输出字符串结果为abc,请问这是为什么啊?