返回信息流在这个循环里,没有重新分配buffer数组的语句,是怎么实现多次调用不冲突的?
我想明白了,那行*(pbuffer-1)=‘\0’;就是答案,多谢大家指点
#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] ; /* 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) /* Check we actually got some?/
{
printf("\nOut of memory - ending program.");
return 1; /* 匛xit if we didn't */
}
/* 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;
}
这是一条镜像帖。来源:北邮人论坛 / cpp / #93911同步于 2016/11/16
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
[问题]看到一段代码,有个小小问题没明白
bluminFlower
2016/11/16镜像同步7 回复
订阅后,新回复会通过你的通知中心匿名送达。
7 条回复
buffer数组在for循环中是被重复赋值的,但是在每次结束之前,使用了malloc给指针分配了内存,strcpy将数组值复制给了指针指向的那段内存,下一次循环开始时前面的数据不会丢失。
【 在 xiaobing307 的大作中提到: 】
: 每次覆盖原来的
对的,我明白这点。
但是如果第i次输入的比i+1的输入长的情况,i+1的赋值并不会受到i的输入影响,这是为什么?
我没看懂每次循环中有格式化buffer数组的操作。。。
【 在 guo1994 的大作中提到: 】
: buffer数组在for循环中是被重复赋值的,但是在每次结束之前,使用了malloc给指针分配了内存,strcpy将数组值复制给了指针指向的那段内存,下一次循环开始时前面的数据不会丢失。
不好意思,我的问题没说清楚,前面忙别的又没及时回复。
你能再看看我楼上的补充吗?
i+1的赋值不受i次的影响是因为for循环中输入字符串结束之后,有一句
*(pbuffer - 1) = '\0';
这样strcpy的字符串就到此为止,不会复制第i次多出的那段长度的字符串,从而指针所指向的内存不会被破坏。
i+1时,最后一个字符后添加'\0',c字符串以'\0'结束。
*(pbuffer - 1) = '\0'; /* Add terminator */
【 在 bluminFlower 的大作中提到: 】
: 对的,我明白这点。
: 但是如果第i次输入的比i+1的输入长的情况,i+1的赋值并不会受到i的输入影响,这是为什么?
: 我没看懂每次循环中有格式化buffer数组的操作。。。