Cast to Char*

Started by
13 comments, last by umbrae 19 years, 7 months ago
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.
Advertisement
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.
Vector2::operator char* ()
{
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
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 mike25025
<memory leak>
Quote:Original post by Oluseyi
Quote: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.
Thats why i made it static... or did i miss a thing?

Thermo
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.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

This topic is closed to new replies.

Advertisement