我正在学习C但我仍然是一个菜鸟.我正在编写一个程序作为动态内存分配练习,它从未知长度的用户获取文本,并返回此文本,没有空格,制表符,特殊字符或数字.该程序似乎工作正常,但有些文本似乎由于未知原因而被更改为未知字符.这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *pstring;
pstring = (char *)malloc( sizeof(char));
char c = '$';
int i = 0;
while(c != '\n')
{
c = getchar();
if(isalpha(c))
{
pstring[i] = c;
realloc(pstring, (i+2)*sizeof(char));
i++;
}
}
int j;
for(j = 0; j < i; j++)
{
printf("%c", pstring[j]);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)