<分区>
我正在尝试获取动态内存分配,我只想让我的程序从用户的字符串中获取一个字符串和应该打印的最大字符数,然后只输出字符串直到我用 calloc
分配的字符数。当我运行该程序时,它完全无视我使用 calloc()
为它设置的限制,只是打印出整个字符串。
我尝试使用 malloc
但得到了相同的结果。另外,当我第一次尝试打印输入的文本时,我取消了对文本的引用,但它导致程序在您输入要打印的字符串后停止。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int max;
char *text = NULL;
printf("\n\n");
printf("Please enter the limit for the string as a positive integer: \n");
scanf("%d", &max);
text = (char *)calloc(max, sizeof(char));
if (text != NULL)
{
printf("Please enter the string you want printed: \n");
scanf(" "); //read in next character so it pauses
gets(text);
printf("Inputted text is : %s\n", text);
}
free(text);
text = NULL;
return 0;
}
是的,我知道,我收到了 gets
不安全的警告,但我是从教程中观看的,并且讲师的版本已构建并运行良好。即使我使用 scanf
将字符串读入文本,结果也是一样的。
使用 fgets()
修改代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int max;
char *text = NULL;
printf("\n\n");
printf("Please enter the limit for the string as a positive integer: \n");
scanf("%d", &max);
text = (char *)calloc(max, sizeof(char));
if (fgets(text, max, stdin))
{
printf("Please enter the string you want printed: \n");
fgets(text, max, stdin);
text[strcspn(text, "\n")] = '\0';
printf("Inputted text is : %s\n", text);
}
free(text);
text = NULL;
return 0;
}
我更改了我的代码以使用 fgets
并进行了一些更正。它返回的字符比用户输入的“最大值”少 1 个。另外,使用 fgets
是否意味着我不需要为 calloc
操心?