加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

我怎样才能编写一个在c中返回字符串的函数?

发布时间:2020-12-16 10:18:19 所属栏目:百科 来源:网络整理
导读:当我尝试使用printf(“%s”,course_comment(1.0));来尝试调用我的函数时,程序崩溃了.这是我的功能: char *course_comment(float b) { if(b 2.0) return("Retake"); } 为什么会崩溃?我该如何解决? 解决方法 如果你的字符串是常量并且无意修改结果,那么使
当我尝试使用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克隆字符串(并且不要忘记释放它):

#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,"Do not retake %f",b);
    }
  return strdup (result);
}

int main()
{
  char *comment;

  comment = course_comment (1.0);
  printf ("Result: %sn",comment);
  free (comment); // Don't forget to free the memory!

  comment = course_comment (3.0);
  printf ("Result: %sn",comment);
  free (comment); // Don't forget to free the memory!

  return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读