繁体   English   中英

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

[英]How can i make C program that scans user's input(text) and save it on a dynamic string

我想使用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个警告c[i]=(char*)malloc(sizeof(char));

警告:赋值在没有强制转换的情况下从指针生成整数[默认启用]

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

分段故障(核心转储)

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

谢谢!

只需更换它

   c[i]=(char*)malloc(sizeof(char));

有了这个

   c = (char*)malloc(sizeof(char));

并删除强制转换,你不需要在C

   c = malloc(sizeof(char));

尝试这个

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

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

正如@Dabo所说,调整作业。

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;
}

编辑:修复

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM