How can i make C program that scans user's input(text) and save it on a dynamic string -
i want read input user(text) using c program , here 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 compiles there 1 warning @ c[i]=(char*)malloc(sizeof(char));
:
warning: assignment makes integer pointer without cast [enabled default]
this program works succesfully if remove x=0
code there is:
segmentation fault (core dumped)
what should change on code can work without warnings or useless random variable x=0
work.
thank you!
as said @dabo, adjust assignment.
c = malloc(sizeof(char));
following additional suggestions:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { // use size_t rather int index size_t i=0; char *c; c = malloc(1); if (c == null) return 1; // out of memory while(1){ // detect eof condition, use type `int` 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); // practice allocated free memory free(c); return 0; }
edit: fixed
Comments
Post a Comment