Jump to content
  • Advertisement
Sign in to follow this  
Axiverse

Cast to Char*

This topic is 5408 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
Advertisement
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

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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 ;)

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!