NeviJ
NeviJ

Reputation: 81

Convert decimal to roman in C - how to return string from function?

Simple function to convert decimal numbers into roman, but how can i return this string from function? I tried this solution but my program crashes.

char roman(int number)
{

char ROMAN[][3] = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };

int NUM[] = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; 

int i;

char buff[100]="\0";

for(i = 0; number > 0 && number < 3999; i++)
  while(number/NUM[i]){
      strcat(buff,ROMAN[i]);
      number -= NUM[i];
  }

return buff;

}

In main I got:

printf("\nAfter change: %s",roman(decimal_number));

Thanks for help.

Upvotes: 1

Views: 454

Answers (1)

Scott Hunter
Scott Hunter

Reputation: 49893

buff is not a single char; it is an array of them. So you'd have to declare the return type of your function accordingly.

But then you have the problem that the string is local to your function; it (conceptually) "goes away" when you return.

Your roughly 2 choices are:

  1. Pass buff as a parameter. (In this case, you wouldn't need to return it.)
  2. Use dynamic allocation (malloc) to allocate the space for buff.

Upvotes: 1

Related Questions