【问题标题】:C: read string into dynamic arrayC:将字符串读入动态数组
【发布时间】:2022-01-05 02:01:18
【问题描述】:

您好,我正在尝试将“无限”长度的用户输入读入 char 数组。它适用于较短的字符串,但对于超过 30 个字符,程序会崩溃。为什么会发生这种情况,我该如何解决?

#include <stdio.h>
#include <stdlib.h>

char* read_string_from_terminal()//reads a string of variable length and returns a pointer to it
{
    int length = 0; //counts number of characters
    char c; //holds last read character
    char *input;

    input = (char *) malloc(sizeof(char)); //Allocate initial memory

    if(input == NULL) //Fail if allocating of memory not possible
    {
        printf("Could not allocate memory!");
        exit(EXIT_FAILURE);
    }

    while((c = getchar()) != '\n') //until end of line
    {
        realloc(input, (sizeof(char))); //allocate more memory
        input[length++] = c; //save entered character
    }

    input[length] = '\0'; //add terminator
    return input;

}

int main()
{
    printf("Hello world!\n");
    char* input;
    printf("Input string, finish with Enter\n");
    input = read_string_from_terminal();
    printf("Output \n %s", input);
    return EXIT_SUCCESS;
}

【问题讨论】:

  • realloc(input, (sizeof(char))); //allocate more memory 这个评论是错误的。将 1 个字节重新分配到 1 个字节不会再分配内存。忽略从realloc() 返回的内容也很糟糕。
  • 另外别忘了给终结者分配空间。
  • 这似乎有效:realloc(input, (sizeof(char)*length+1));
  • @t1msu 这似乎有效:realloc(input, (sizeof(char)*length+1)); 你将返回的指向分配给什么?此外,getchar() 返回 int,而不是 char
  • 不要强制转换 malloc 和好友的返回值。

标签: c


【解决方案1】:

realloc(input, (sizeof(char))); //allocate more memory 只分配 1 个char。不是 1 更多 char@MikeCAT

(sizeof(char)*length+1) 在语义上是错误的。应该是(sizeof(char)*(length+1)),但由于sizeof (char) == 1,它没有功能上的区别。

空字符需要空间。 @MikeCAT

应该测试重新分配失败。

char c 不足以区分来自getchar() 的所有 257 个不同响应。使用intgetchar() 可能会返回 EOF@Andrew Henle

次要:将size_t 用于数组索引比使用int 更好。 int 可能太窄了。

最后代码需要做类似的事情:

size_t length = 0;
char *input = malloc(1);
assert(input); 
int c;
...
while((c = getchar()) != '\n' && c != EOF) {
  char *t = realloc(input, length + 1);
  assert(t); 
  input = t;
  input[length++] = c;
}
...
return input;

int main(void) {
  ...
  input = read_string_from_terminal();
  printf("Output \n %s", input);
  free(input);
  return EXIT_SUCCESS;
}    

【讨论】:

  • 附带说明,代码应该返回 NULL 是第一个 getchar() 返回 EOF 以指示调用代码结束文件。
猜你喜欢
  • 1970-01-01
  • 2017-08-27
  • 2011-10-19
  • 1970-01-01
  • 1970-01-01
  • 2011-08-01
  • 1970-01-01
  • 2021-03-12
相关资源
最近更新 更多