我想使用 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/