c - 在 C 中使用 realloc 按字符读取输入字符

标签 c memory-management realloc

我想逐个读取输入的字符并将其作为一个单词保存到 char* 数组中。我不知道输入会有多长时间,所以我想动态分配内存。当 char 为空白时,程序结束。我怎样才能使用 realloc 做到这一点? 这是我的代码:

#include <stdio.h>
int main(void) {
    char *word=malloc(1*sizeof(char));
    char c;
    int numOfChars=0;
    c=getchar();
    word[0]=c;
    numOfChars++;
    while((c=getchar())!=' '){
        numOfChars++;
        realloc(word,numOfChars);
        word[numofChars-1]=c;
    }
    printf("%s", word);

    return 0;
}

示例输入:Word 示例输出:Word

最佳答案

程序可以看成下面的样子。考虑到输入会被缓冲和填充,直到输入新的行字符,该行字符也是空白字符。如果要使用格式说明符 %s 输出结果字,则结果字必须以零结尾。

#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>

int main( void )
{
    int c;
    size_t n;
    char *word;
    char *tmp;

    n = 0;
    word = malloc( n + 1 );
    word[n++] = '\0';

    printf( "Enter a word: " );

    while ( ( c = getchar() ) != EOF && !isspace( c ) && ( tmp = realloc( word, n + 1 ) ) != NULL )
    {
        word = tmp;
        word[n-1] = c;
        word[n++] = '\0';
    }

    printf( "You've entered \"%s\"\n", word );

    free( word );
}        

程序输出可能是这样的

Enter a word: Hello
You've entered "Hello"

关于c - 在 C 中使用 realloc 按字符读取输入字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37344876/

相关文章:

c - 使用 beaglebone Black SPI 在 DIP203-6 LCD 屏幕上显示字符

winapi - 大地址感知标志如何在 64 位计算机上用于 32 位应用程序?

Java 库大小

c - 回复 : Struct Array with Varying Size Structs--Clarification

c - 为什么 realloc 在此 while 循环中不起作用?

c - 制作一个匹配两个字符串(如果它们相同)的程序

c - 我怎样才能让这段代码重复主要功能

c - 为什么 GCC 会对 ARM Cortex-A9 产生非法的未对齐访问

c - 学习 'Linked lists' 的速度太快,但又不太熟悉指针? #C语言初学者

c - 在二维数组 c 上使用 realloc