简体   繁体   中英

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

I want to read input from user(text) using a C program and here is my code:

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

This program when it compiles there is 1 warning at c[i]=(char*)malloc(sizeof(char)); :

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

This program works succesfully but if i remove x=0 from the code there is:

Segmentation fault (core dumped)

What should i change on this code so it can work without warnings or a useless random variable like x=0 to work.

Thank you!

Simply replace this

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

with this

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

and remove cast, you don't need it in C .

   c = malloc(sizeof(char));

Try this

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

As said by @Dabo, adjust the assignment.

c = malloc(sizeof(char));

Following are additional suggestions:

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

Edit: fixed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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