char *VectorToString(const VECTOR v)
{
char *str = (char *)malloc(50);
sprintf(str,"VECTOR (%f,%f,%f) ",v.x,v.y,v.z);
return str;
}
vector to string function
In C, how can be done this (I get errors,I cannot do free before return the string)
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
-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]
[edited by - _Twiggie_ on March 23, 2004 5:23:21 PM]
He''s passing in a pointer to a character by reference.
That should work also.
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 StonicusError: You''re passing a char to a function expecting a char *. Don''t dereference there.snprintf(*str, len, "%f,%f,%f", v.x, v.y, v.z);
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;
}
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
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement