c - 我如何制作扫描用户输入(文本)并将其保存在动态字符串上的 C 程序

标签 c string dynamic

我想使用 C 程序读取用户(文本)的输入,这是我的代码:

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

int main(){
    int i=0,x=0;
    char *c;
    c[i]=(char*)malloc(sizeof(char));
    while(1){
        c[i]=getc(stdin);
        if(c[i]=='\n')
            break;
        i++;
        realloc(c, i+1 );
    }
    c[i]='\0';
    //printf("\n%d",strlen(c));
    printf("\n\n%s",c);
return 0;
}

此程序在编译时在 c[i]=(char*)malloc(sizeof(char)); 处有 1 个警告:

warning: assignment makes integer from pointer without a cast [enabled by default]

此程序运行成功,但如果我从代码中删除 x=0,则:

Segmentation fault (core dumped)

我应该对此代码进行哪些更改,以便它可以在没有警告或无用的随机变量(如 x=0)的情况下工作。

谢谢!

最佳答案

如@Dabo所说,调整assignment。

c = malloc(sizeof(char));

以下是额外的建议:

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

int main() {
    // Use size_t rather than int for index
    size_t i=0;
    char *c;
    c = malloc(1);
    if (c == NULL) return 1; // Out of memory  
    while(1){
        // To detect EOF condition, use type `int` for get() result
        int ch = getc(stdin);
        if(ch == EOF || ch == '\n') {
            break;
        }
        c[i++] = ch;
        // Important, test & save new pointer 
        char *c2 = realloc(c, i+1 );
        if (c2 == NULL) return 1; // Out of memory  
        c = c2;
    }
    c[i] = '\0';
    // Use %zu when printing size_t variables
    printf("\n%zu",strlen(c));
    printf("\n\n%s",c);
    // Good practice to allocated free memory
    free(c);
   return 0;
}

编辑:修复

关于c - 我如何制作扫描用户输入(文本)并将其保存在动态字符串上的 C 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22897134/

相关文章:

c - 尝试填充二维矩阵时出现段错误(核心转储)错误

c 受 printf 影响的最大数组大小

c - 如何确定 foo.c 中的哪些预处理器宏源自 bar.h?

python - 在 Python 中查找字符串中的字符数

ruby - 全部大写到正常大小写

javascript - R Shiny : Dynamic tabs within multiple navbarPage tabPanels

java - 使用 RecyclerView 和 GridLayoutManager 向布局添加动态按钮

c - #define func(t, a, b){ t temp;温度=a; a=b; b=温度;}

r - 将单列拆分为四列并计算 R 中的重复模式

python - 是否可以动态地在 python 对象中生成属性?