gpt4 book ai didi

c - 使用 malloc() 进行多个输入?

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

好吧,我知道 malloccalloc 可用于动态分配,但作为 C 的新手,我不知道如何使用为输入多个而分配的内存像 TC++ 示例中的输入一样,我们有此代码

#include <stdio.h>
#include <string.h>
#include <alloc.h>
#include <process.h>

int main(void)
{
char *str;

/* allocate memory for string */
if ((str = (char *) malloc(10)) == NULL)
{
printf("Not enough memory to allocate buffer\n");
exit(1); /* terminate program if out of memory */
}

/* copy "Hello" into string */
strcpy(str, "Hello");
/* display string */
printf("String is %s\n", str);
/* free memory */
free(str);

return 0;
}

在这样的代码中,我们将 Hello 放置到我们现在分配的内存中,这应该会给我们留下 4 个以上的字符空间,我们也应该向这些空间添加数据。

当用户被询问输入数量时,他说 10 或 100,然后程序输入数据并存储它们并将该数据打印到屏幕上,我想实现这个想法。

最佳答案

如果您想附加到经过 malloc 处理的字符串,请使用 strcat

str = malloc(20);
...
/* copy "Hello" into string */
strcpy(str, "Hello");
strcat(str, ", world!");
/* display string */
printf("String is %s\n", str); /* will print 'Hello, world!' */

关于c - 使用 malloc() 进行多个输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13528108/

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