gpt4 book ai didi

c - C语言解析输入并自动为字符分配空间

转载 作者:太空宇宙 更新时间:2023-11-04 08:21:08 25 4
gpt4 key购买 nike

我几个月前开始学习使用 Python 编程,我决定学习 C,因为我对低级语言感兴趣,这些语言可以让我更接近计算机硬件。我试图从 C 中的用户那里获得一些输入,并且我正在编写自己的小输入解析器。我在这里遇到了一些麻烦:

#include <stdio.h>

char prompt()
{
char resp[]; // Create a variable for the users response

for (int i = 0; i < 1000; ++i)
{
char letter = getchar(); // Get character
if (letter == '\n') // If the user hits enter break the loop
{
break;
}
else // Otherwise append the character to the response array
{
resp[i] = letter;
}
}

return resp[]; // Return the response array
}

int main() {
return 0;
}

我收到此代码的错误。错误特别指出:

error:    definition of variable with array type needs an explicit size or an initializer
char resp[];

我认为我必须为数组定义一个设定值或立即为其赋值。如果 C 中的数组必须具有定义的值,我不明白如何在用户键入输入时增加字符数组。我在想使用指针或内存管理可能会奏效,但我还没有学到很多关于这些东西的知识,所以如果你有一个涉及指针的解决方案,如果你能简要解释一下代码,那将对我有很大帮助是在做。与此同时,我将尝试找到解决方案。

最佳答案

您可能想要分配内存,这是您的做法>

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

char* prompt()
{
char* resp; // Create a variable for the users response
int i;
resp = malloc(sizeof(char));//allocate space for one char
for (i = 0; i < 1000; ++i)
{
resp = realloc(resp, sizeof(char)*(i+1));//allocate space for one more char
char letter = getchar(); // Get character
if (letter == '\n') // If the user hits enter break the loop
{
break;
}
else // Otherwise append the character to the response array
{
resp[i] = letter;
}
}

return resp; // Return the response array
}

int main() {
char* answer = prompt();
printf("answer is %s\n", answer);
return 0;
}

这会起作用,但强烈不建议这样做,因为您永远不会free()您分配的内存。

编辑>怎么做?您可能希望避免创建新函数并在 main() 中完成所有操作,在这种情况下,当您不再需要变量时只需调用 free(resp);

关于c - C语言解析输入并自动为字符分配空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33381931/

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