当我尝试使用 printf("%s",course_comment(1.0) );
调用我的函数时,程序崩溃了。这是我的功能:
char *course_comment(float b)
{
if(b < 2.0)
return("Retake");
}
为什么会崩溃?我该如何解决?
最佳答案
如果您的字符串是常量并且无意修改结果,则使用字符串文字是最佳选择,例如:
#include <stdio.h>
static const char RETAKE_STR[] = "Retake";
static const char DONT_RETAKE_STR[] = "Don't retake";
const char *
course_comment (float b)
{
return b < 2.0 ? RETAKE_STR : DONT_RETAKE_STR;
}
int main()
{
printf ("%s or... %s?\n",
course_comment (1.0),
course_comment (3.0));
return 0;
}
否则,您可以使用 strdup
克隆字符串(并且不要忘记 free
它):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *
course_comment (float b)
{
char result[256];
if (b < 2.0)
{
snprintf (result, sizeof (result), "Retake %f", b);
}
else
{
snprintf (result, sizeof (result), "Do not retake %f", b);
}
return strdup (result);
}
int main()
{
char *comment;
comment = course_comment (1.0);
printf ("Result: %s\n", comment);
free (comment); // Don't forget to free the memory!
comment = course_comment (3.0);
printf ("Result: %s\n", comment);
free (comment); // Don't forget to free the memory!
return 0;
}
关于c - 我如何编写一个返回字符串的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4958758/