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

标签 c c-strings

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/

相关文章:

c - 为什么C中void main函数内的参数值初始化为1?

c - 在 Briceno 等人的 A5/2 实现中,他们延迟了 LSFR 周期而不运行时钟周期函数。有人可以帮我理解吗?

c - 以整数形式返回 C 字符串数组?

c - 按顺序打印的动态数组

c - 写一个函数的定义,isReverse

c - 从 fifo 标准输出打印到屏幕失败

arrays - 使用 strncpy() 时缓冲区溢出内存困惑?

c++ - 将 cstring 转换为驼峰式

c - 使用fgetc读取单词?

c++ - 是否可以在需要字符串文字时使用 std::string::c_str() ?