Archived

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

q2guy

vector to string function

Recommended Posts

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
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
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
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
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

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
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