我怎么能写返回在C字符串的函数? [英] how can i write a function that returns a string in c?

查看:75
本文介绍了我怎么能写返回在C字符串的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用的printf(%S,course_comment(1.0))打电话给我的功能; ,程序崩溃。这是我的功能:

When I try calling my function using printf(" %s",course_comment(1.0) );, the program crashes. This is my function:

char *course_comment(float b) 
{ 
   if(b < 2.0) 
     return("Retake"); 
}

为什么它会崩溃?我怎样才能解决这个问题?

Why does it crash? How can I fix it?

推荐答案

如果你的字符串是常数,也无意修改结果,字符串的工作是最好的选择,例如:

If your strings are constants and there is no intention to modify the result, working with string literals is the best choice, e.g.:

#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 克隆字符串(不要忘了免费吧):

Otherwise, you can use strdup to clone the string (and don't forget to free it):

#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字符串的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆