0

I have to make a function that has a float as parameter, and the function will return that number in words (As a string)

i.e: function(12.0) will return twelve as a string

But I have some problems returning the string, it returns some weird data, I have this code:

            char* function (float number)
            {
                char str[] = "test";
                strcat(str, " char");
                return str;
            }

            int main()
            {
                char *test = function(5.0); 
                printf("Hi %s", test);
            }

That always returns a different thing:

            Hi u.ª╣D
            Hi uêõWÛ

I don't know how to fix it, because I really need to use strcat to do things like 'one thousand ten' saving time and lines of code, and it's not possible if I define char str as a pointer...

I'm using Dev-C++ 5.11

Thank you!

I searched a few days but noone of the answers worked with what I need, because they define the string as a pointer or use more than 1 parameter in the function (it only has to receive 1 float parameter, no more parameters are accepted)

sort72
  • 66
  • 1
  • 6

1 Answers1

1

str is local to function and will be destroyed once control exits function.

Hence you can try as below.

            char* function (float number)
            {
                char *str = malloc(30);
                strcpy(str, " test");
                strcat(str, " char");
                return str;
            }

            int main()
            {
                char *test = function(5.0); 
                printf("Hi %s", test);
            }
kiran Biradar
  • 12,700
  • 3
  • 19
  • 44