【问题标题】:where did i go wrong in this piece of code这段代码我哪里出错了
【发布时间】:2017-01-05 17:40:12
【问题描述】:
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 中使用此函数后获取字符串作为输入我似乎没有得到输出这有什么问题?

【问题讨论】:

  • 为什么返回int?你的函数应该返回一个char *,而return *x;应该是return x;
  • 您还忘记了字符串的 0 终止符。
  • 我看到了一些错误,首先您读取 char 两次而不是读取一次并使用您已经读取的值,因此您可能最终会跳过循环中要查找的值。此外,您重新分配了错误的数量,应该是sizeof(char)*(i+1),最后为什么要在返回 int 的函数中返回字符指针?内存大小取决于系统,因此它可能是也可能不是您要转换的正确值。
  • @MiltoxBeyond sizeof(char)*(i+1) 应该是 sizeof(char)*(i+2)
  • 除了上面的 cmets,ch 应该是 int,而不是 char,因为值 EOF 可能不适合 char

标签: c c-strings


【解决方案1】:

我是这样做的:

#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...



*/

【讨论】: