Function return safe or not ?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
char* KandM(uint32 geld)
{
		char *buf = new char[10];
		if (geld > 999999)
		{
			// Miljoenen
			sprintf(buf, "%.1fm", geld / 1000000);
		}
		else if (geld > 999)
		{
			// Duizenden
			sprintf(buf, "%.1fk", geld / 1000);
		}
		else
		{
			// Honderden
			sprintf(buf, "%i", geld);
		}
		return buf;
}


and

char *test = KandM(c->transported);


is it safe to cast a function with return like this ?
or could it cause any kind of trouble ?

Since im not a pro at C++..


edit: when testing it the numbers gone wild..
an issue i couldnt solve.. maybe any of you can see the mistake ?
Last edited on
You are not doing anything illegal. Just make sure you delete[] the result of the function.

1
2
3
char* s = KandM( ... );
cout << s << endl;
delete[] s;


Since you are using C++, though, you would be better to just use strings and convert stuff using a stringstream.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
string KandM(Money geld)
{
  ostringstream result;

  if (geld > 999999)
  {
    // Miljoenen
    result << (geld / 1000000) << "m";
  }
  else if (geld > 999)
  {
    // Duizenden
    result << (geld / 1000) << "k";
  }
  else
  {
    // Honderden
    result << geld;
  }

  return result.str();
}

Then you can use it guilt-free:

1
2
3
4
cout << KandM( ... ) << endl;
// or
string s = KandM( ... );
cout << s << endl;


Hope this helps.
Thnx for the fast reply !

but found whats wrong..

instead of tranfering into a text with %s i did it with %i..

little dumb :p
anyway, thanks for the tips!
instead of tranfering into a text with %s i did it with %i..
That's what I saw when I first looked...
Nah its not in this thread, but:
sprintf(test, "# [Company:%s] [Cargo:%s] [Passengers:%s] [Mail:%s]",c->name, kcar, kpax, kmail);

anyway.. you said deleting the new char..
Where should i do that.. because if i delete it before the return it will be faulty.. when i add it after the return it wont be handled..

also got a new issue.. when the number is above 999 it just saids 0.0k ...

tried this :
char *buf = new char[10];
Money rekendgeld = geld;
if (geld > 999999)
{
// Miljoenen
sprintf(buf, "%.1fm", rekendgeld / 1000000);
}
else if (geld > 999)
{
// Duizenden
sprintf(buf, "%.1fk", rekendgeld / 1000);
}
else
{
// Honderden
sprintf(buf, "%i", rekendgeld);
}
return buf;

but also returned 0.0k if higher then 999...
Last edited on
It has to be handled. I gave you an example above. Good luck!
Topic archived. No new replies allowed.