vector to string function

Started by
9 comments, last by q2guy 20 years, 1 month ago
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;
}
Advertisement
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
void VectorToString(const VECTOR & v, char *& str, int len ){  snprintf(str, len, "%f,%f,%f", v.x, v.y, v.z);} 
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]
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.
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.
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.
Thanks to all, this way works well
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;
}
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
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

My Page davepermen.net | My Music on Bandcamp and on Soundcloud

This topic is closed to new replies.

Advertisement