Search code examples
cfloating-pointcharsubroutine

Converting a float to string in a subroutine in C


I am attempting to make a program in c where I use a subroutine to process some variables in a subroutine and return them as an array. For instance I have the numbers 2.5 and 3.5 and the subroutine multiplies these numbers by a certain value and then returns them as a string containing the two values.

Below is the program I am trying to use:

#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

char test_subroutine(float x,float y)
{
    float a=105.252342562324;
    float b=108.252234256262;
    float d;
    float e;
    char var;

    d=x*a;
    e=y*b;

    sprintf(var,"%0.2f %0.2f",d,e);

    return var;
}



int main()
{
    char variable;
    variable=test_subroutine(2.5,3.5);

}

When trying to compile I get the following error:

testrun.c: In function ‘char test_subroutine(float, float)’:
testrun.c:21:31: error: invalid conversion from ‘char’ to ‘char*’    [-fpermissive]
sprintf(var,"%0.2f %0.2f",d,e);
                           ^
In file included from testrun.c:1:0:
/usr/include/stdio.h:364:12: error:   initializing argument 1 of ‘int sprintf(char*, const char*, ...)’ [-fpermissive]
extern int sprintf (char *__restrict __s,

How do I resolve this issue?


Solution

  • You're trying to use sprintf to write data to a char. Look at the declaration of the sprintf function, as your compiler suggests:

    int sprintf(char*, const char*, ...)
    

    It takes a char* as first argument, that is: a pointer to a buffer where to store the formatted string that is generated.

    You should use it like this (please pay attention to all the changes I made):

    // Return the allocated buffer, which is char*, not char.
    char *test_subroutine(float x,float y)
    {
        float a=105.252342562324;
        float b=108.252234256262;
        float d;
        float e;
    
        char *var = malloc(100); // Allocate a buffer of the needed size.
    
        d=x*a;
        e=y*b;
    
        sprintf(var,"%0.2f %0.2f",d,e); // Sprintf to that buffer
    
        return var;
    }
    
    
    
    int main()
    {
        char *variable;
        variable = test_subroutine(2.5,3.5);
        free(variable); // Free the buffer allocated by test_subroutine()
    }