gpt4 book ai didi

C:将字符串读入动态数组

转载 作者:行者123 更新时间:2023-11-30 15:07:53 25 4
gpt4 key购买 nike

嗨,我正在尝试将“无限”长度的用户输入读取到字符数组中。对于较短的字符串,它工作得很好,但对于超过 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(输入, (sizeof(char)));//分配更多内存仅分配1个char。没有 1 个更多 字符@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;
}

关于C:将字符串读入动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37839153/

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