Vector2::operator char* ()
{
return "{" + (char*)x + ", " + (char*)y + ", " + "}";
};
doesn't seem to work.
Cast to Char*
uhh... i'm new at C++ and i'm can't figure out hot to convert a float to a char *
In short, you can't.
Look into sprintf or similar. You could also do it using stringstreams if you don't mind using std::string.
Look into sprintf or similar. You could also do it using stringstreams if you don't mind using std::string.
Vector2::operator char* ()
{
char* buf = new char[64];
sprintf(buf,"{%f, %f}",x,y);
return buf;
};
{
char* buf = new char[64];
sprintf(buf,"{%f, %f}",x,y);
return buf;
};
oO
#include <iostream>
#include <iosfwd>
#include <sstream>
Vector2::operator char* ()
{
static std::string result;
std::strstream thestream;
thestream << "{" << x << ", " << y << " }";
result = thestream.str();
return result.c_str();
};
Compiles for me :)
Thermo
#include <iostream>
#include <iosfwd>
#include <sstream>
Vector2::operator char* ()
{
static std::string result;
std::strstream thestream;
thestream << "{" << x << ", " << y << " }";
result = thestream.str();
return result.c_str();
};
Compiles for me :)
Thermo
Quote:Original post by Axiverse
uhh... i'm new at C++ and i'm can't figure out hot to convert a float to a char *Vector2::operator char* (){ return "{" + (char*)x + ", " + (char*)y + ", " + "}";};
doesn't seem to work.
You see, the problem is that you try to add a char pointer (some address) to an address you got from converting your number to an address and so on, that doesn't work.
Remember: All a char* pointer is is really this:
char* ptr = "I am a block of data somewhere in memory";
now ptr points to the first char of that data.
so that ptr + x really yields a pointer to the "x"th char of that data.
*(ptr + x) gives you back that exact single char, and ptr[x] is just another way to write that.
Hope that clears it up a bit.
For further reference have a look at the book Thinking in C++, 2nd Edition by Bruce Eckel.
Thermo
Quote:Original post by OluseyiQuote:Original post by mike25025
<memory leak>
Hey, who says the caller won't delete[] the string? You are kinda unfair :)
Thermo/Konfu
PS: I need to get rid of these D*NG online aliases... they spawn like... Porings ;)
Wouldn't Konfusius' solution also cause problems? The std::string allocated will go out of scope when the function is exited and therefore you can't be sure that the char* is still valid.
Quote:Original post by Konfusius
Thats why i made it static... or did i miss a thing?
Thermo
Which makes your code non-threadsafe and non-reentrant. If somebody does another such conversion before having copied out the pointed-at data... you're screwed.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement