[英]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: 我想使用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;
}
This program when it compiles there is 1 warning at c[i]=(char*)malloc(sizeof(char));
编译时该程序在
c[i]=(char*)malloc(sizeof(char));
有1个警告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: 该程序成功运行,但如果我从代码中删除
x=0
,则:
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. 我应该对此代码进行更改,以便它可以在没有警告或无效的随机变量(如
x=0
下工作。
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
。
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. 正如@Dabo所说,调整作业。
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 编辑:修复
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.