#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void main(){
int c;
char *p=malloc(50*sizeof( char ));
//char *p;
while((c = getchar()) != '\n' )
{
*p++ = c;
*p='\0';
// printf("%s",p);
}
printf("\nThis is outside while %s",p);
}
我无法在外面输出,请帮忙!
答案 0 :(得分:1)
使用索引。这将允许您修改字符串的内容而不更改指针的值。您还可以使用索引来阻止访问无效数据。
int c;
int i = 0;
char *p=malloc(50*sizeof( char ));
while((c = getchar()) != '\n' && i < 49 )
{
p[i] = c;
++i;
}
p[i] = '\0';
printf("\nThis is outside while %s",p);