How can I write a function that returns a string in c?

When I try to call my function with 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 is he falling? How can i fix this?

+3
source share
7 answers

If your strings are constants and there is no intention to change the result, then it is best to work with string literals, for example:

#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;
}

Otherwise, you can use the strdupstring to clone (and don't forget it 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;
}
+4
source

/ , "course_comment", , , C "int". , .. .

, , ( ). , "f", 1.0, , int.

- , - :

#include <stdio.h>

const char *course_comment(float b); // <- fn prototype


int main(int argc, char *argv[]) {

    printf(" %s",course_comment(1.0f));


}


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

, const char *, .

, b 2.0? , ? ?

+2

.

, else ... , , !

my2c

+1

NULL- 1.0 .

, printf:

printf(" %s", NULL);

:

  • gcc -Wall
+1

. , , - :

main.c

#include "some_other_file.h"

int main()
{
  printf(" %s", course_comment(1.0f) );
  return 0;
}

some_other_file.h

#ifndef YADA_YADA_H
#define YADA_YADA_H 

const char* course_comment(float b);

#endif

some_other_file.c

static const char COMMENT_RETAKE [] = "Retake";



const char* course_comment(float b) 
{ 
  const char* result;


  if(b < 2.0f)
  {
    result = COMMENT_RETAKE;
  }
  else
  {
    result = ""; /* empty string */
  }

  return result;
}

, 1.0f 1.0 . , .

+1

, return "blah", const char*.

0

Source: https://habr.com/ru/post/1791239/


All Articles