返回信息流#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define maxline 10
int getline(char *string,int MAXLINE);
/*打印长度大于5个字符的输入行*/
int main()
{
int len;
char *str;
if( (str =(char *) malloc(maxline * sizeof(char))) == NULL)
{
printf("can not allcation the size\n");
return -1;
}
while ((len = getline(str,maxline)) > 0)
{
if (len > 5)
{
while ( *str != '\0')
{
printf("%c", *str);
str++;
}
printf("\n");
}
}
free(str);
return 0;
}
int getline(char *string,int MAXLINE)
{
int i, c;
for (i = 0; i < MAXLINE-1 && (c = getchar()) != '#' && c != '\n'; i++)
{
*string = c;
string++;
}
{
*string = c;
string++;
} */
*string = '\0';
return i;
}
这是一条镜像帖。来源:北邮人论坛 / cpp / #28673同步于 2009/9/18
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
大家帮我看看这个free用对没?当输入9个字符时出现段错误!!
zbf
2009/9/18镜像同步11 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
不好意思,不好意思,多贴了一行,这个是完整的啦
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define maxline 10
int getline(char *string,int MAXLINE);
/*打印长度大于5个字符的输入行*/
int main()
{
int len;
char *str;
if( (str =(char *) malloc(maxline * sizeof(char))) == NULL)
{
printf("can not allcation the size\n");
return -1;
}
while ((len = getline(str,maxline)) > 0)
{
if (len > 5)
{
while ( *str != '\0')
{
printf("%c", *str);
str++;
}
printf("\n");
}
}
free(str);
return 0;
}
int getline(char *string,int MAXLINE)
{
int i, c;
for (i = 0; i < MAXLINE-1 && (c = getchar()) != '#' && c != '\n'; i++)
{
*string = c;
string++;
}
*string = '\0';
return i;
}
str=(char *)malloc(...)
free(str);
这两句话之间对str进行了修改:str++
这样free时会有问题
str已经不是曾经的str了~~
【 在 zbf 的大作中提到: 】
: 不好意思,不好意思,多贴了一行,这个是完整的啦
: #include<stdio.h>
: #include<stdlib.h>
: ...................
【 在 guo 的大作中提到: 】
: str=(char *)malloc(...)
: free(str);
: 这两句话之间对str进行了修改:str++
: ...................
但是当我重新设置一个指针P指向str,然后变动P,str不变,结果还是错的啊,这是怎么回事啊???
不应该呀
你现在的程序是怎么样的?
再贴上来
另外
如何输入会出现段错误?
【 在 zbf (andy) 的大作中提到: 】
: 但是当我重新设置一个指针P指向str,然后变动P,str不变,结果还是错的啊,这是怎么回事啊???
【 在 guo 的大作中提到: 】
: 不应该呀
: 你现在的程序是怎么样的?
: 再贴上来
: ...................
当输入9个字符回车的时候就出现段错误了,这是按前面修改了的,但还是显示段错误
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define maxline 10
int getline(char *string,int MAXLINE);
/*打印长度大于5个字符的输入行*/
int main()
{
int len;
char *str,*p;
if( (str =(char *) malloc(maxline * sizeof(char))) == NULL)
{
printf("can not allcation the size\n");
return -1;
}
p = str;
while ((len = getline(p,maxline)) > 0)
{
if (len > 5)
{
while ( *p != '\0')
{
printf("%c", *p);
p++;
}
printf("\n");
}
}
free(str);
return 0;
}
int getline(char *string,int MAXLINE)
{
int i, c;
for (i = 0; i < MAXLINE-1 && (c = getchar()) != '#' && c != '\n'; i++)
{
*string = c;
string++;
}
*string = '\0';
return i;
}
。。。
while循环里面的最后加上一句p=str;
你p++之后再去getline(p,maxline)时
p已经不再指向你最初malloc的内存了~~
while ((len = getline(p,maxline)) > 0)
{
if (len > 5)
{
while ( *p != '\0')
{
printf("%c", *p);
p++;
}
printf("\n");
}
}
【 在 zbf 的大作中提到: 】
: 当输入9个字符回车的时候就出现段错误了,这是按前面修改了的,但还是显示段错误
: #include<stdio.h>
: #include<stdlib.h>
: ...................