好吧,我知道malloc
或calloc
可用于动态分配,但作为一个新CI不知道如何使用我输入多个输入,比如例如TC中分配的内存++中,我们有这样的代码使用malloc()进行多输入?
#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时,我想实现这个想法,然后程序输入数据并存储它们并将数据打印到屏幕上。
所以你要根据用户输入分配的大小? –
您可能缺少'#include'指令。如果你想部分填充一些'malloc'-ed或'calloc' -ed动态分配的堆区,你可能需要做一些家务管理,例如,与当前和结束索引或指针。你可能想用'getline'来完全读取一个'malloc'-ed行。 –
在C中,不需要将调用结果强制转换为'malloc()'/'calloc()'。也不建议这样做,因为这可能会隐藏错误,因为在您的示例中很可能是这种情况(请参阅* Basile *的注释)。 – alk