c - 我如何编写一个返回字符串的函数?

标签 c string

当我尝试使用 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/

相关文章:

c++ - 将 char 数组转换为 WCHAR 数组的最简单方法是什么?

gets() 函数中的 CR 字符

C - 字符串连接

c - 如何将 const unsigned char* payLoad 转换为 char* 并复制它?

C - 按值传递和按引用传递不一致

c - getchar() 在此代码中到底做了什么.. [C]

string - 如何检查给定变量值是否为字符串类型

c - 在 C++ 中填充动态大小的数组并使用值

c - 将 'C' 中的字符数组拆分为 CSV

python - 将一系列位传递给文件python