gpt4 book ai didi

c - 这段代码我哪里出错了

转载 作者:行者123 更新时间:2023-11-30 16:51:56 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com