Archived

This topic is now archived and is closed to further replies.

q2guy

vector to string function

Recommended Posts

q2guy    122
In C, how can be done this (I get errors,I cannot do free before return the string)
char *VectorToString(const VECTOR v)
{
	char *str = (char *)malloc(50);

	sprintf(str,"VECTOR (%f,%f,%f) ",v.x,v.y,v.z);

	return str;
}

Share this post


Link to post
Share on other sites
Palidine    1315
you can''t free a string and THEN return the same string. otherwise your solution is fine. if you want to return the string like that, then it''s up to the caller of the function to free what you have malloc''d. another way to do it would be to have the caller pass in a string buffer as an argument to the function, but then you''d have to check to make sure it was long enough.

-me

Share this post


Link to post
Share on other sites
_Twiggie_    122
Sorry about this off-topic question, but in regard to Oluseyi's post, what is this syntax: char *& str and what is it used for? Ive looked on google & elsewhere but hav'nt found anything. I would hate to guess what exactly it is based on the operators used Thanks

[edited by - _Twiggie_ on March 23, 2004 5:23:21 PM]

Share this post


Link to post
Share on other sites
Stonicus    157
He''s passing in a pointer to a character by reference.

void VectorToString(const VECTOR & v, char * str, int len )
{
snprintf(*str, len, "%f,%f,%f", v.x, v.y, v.z);
}

That should work also.

Share this post


Link to post
Share on other sites
Oluseyi    2103
It passes the actual pointer as opposed to a copy of the pointer. In some very complicated instances, the difference can introduce subtle bugs. This isn''t one of them, but this form has no drawbacks.

Share this post


Link to post
Share on other sites
Oluseyi    2103
quote:
Original post by Stonicus
snprintf(*str, len, "%f,%f,%f", v.x, v.y, v.z); 

Error: You''re passing a char to a function expecting a char *. Don''t dereference there.

Share this post


Link to post
Share on other sites
sordid    246
Another, somewhat evil method, is as follows:

char *VectorToString(const VECTOR v) {
static char *str[64];
sprintf(str, "VECTOR (%f,%f,%f) ", v.x, v.y, v.z);
return str;
}

Share this post


Link to post
Share on other sites
davepermen    1047

std::ostream& operator<<(std::ostream& os,const Vector& v) {
os<<"("<<v.x<<";"<<v.y<<";"<<v.z<<")";
return os;
}


i like this way..




If that''s not the help you''re after then you''re going to have to explain the problem better than what you have. - joanusdmentia

davepermen.net

Share this post


Link to post
Share on other sites
davepermen    1047
i''ve seen it''s originated in C. i missed that, because quite some replies had references in, wich won''t work in C.




If that''s not the help you''re after then you''re going to have to explain the problem better than what you have. - joanusdmentia

davepermen.net

Share this post


Link to post
Share on other sites