Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i write a function that returns a string in c?

Tags:

c

string

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?

like image 430
Wasswa Samuel Avatar asked Feb 17 '26 18:02

Wasswa Samuel


2 Answers

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

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

Depending on the order / structure of your program when 'course_comment' is first called - it maybe be undeclared & C will default its return type to an 'int'. Check for compiler warnings when you err.. compile.

Also make sure you understand about function prototypes, when & where they should be used (everywhere basically). I think the 'f' missing on the 1.0 means the argument will be auto cast to an int.

This works - not that I would ever do this:

#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"); 
}
like image 40
David Victor Avatar answered Feb 19 '26 07:02

David Victor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!