小编Nor*_*mer的帖子

C动态内存分配

我正在学习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)

工作正常: 在此输入图像描述

问题是: 在此输入图像描述

c malloc realloc calloc dynamic-memory-allocation

2
推荐指数
1
解决办法
132
查看次数

标签 统计

c ×1

calloc ×1

dynamic-memory-allocation ×1

malloc ×1

realloc ×1