int getstring(void)
{
char *x;
int i = 0;
x = malloc(sizeof(char) + 1);
char ch;
while ((ch = getchar()) != EOF)
{
x[i] = getchar();
x = realloc(x, sizeof(char) + i + 1);
i++;
}
return *x;
}
在 main 中使用此函数后,我试图编写一个函数来获取字符串作为输入,但我似乎没有得到输出,这有什么问题?
最佳答案
我是这样做的:
#include <stdio.h>
#include <stdlib.h>
//-----------------------------------
char* getstring(void)
{
char *x;
int i = 0;
x = malloc(sizeof(char));
int ch;
while ( ((ch = getchar()) != EOF) && (i<99))
{
x[i] = (char)ch;
i++;
x = realloc(x ,sizeof(char)*(i+1));
}
x[i]=0;
return x;
}
//-----------------------------------
int main()
{
char *s;
s=getstring();
printf("\nYou entered : %s\n",s);
free(s);
return 0;
}
//-----------------------------------
/*
On Ubuntu linux you have to press ENTER and ctrl-d at the end of your keyboard input
output:
user@ubuntu1:~/Desktop/getstr$ ./tst
This is a test...
You entered : This is a test...
*/
关于c - 这段代码我哪里出错了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41491368/