Advertisement

semi-interesting pointer/variable question :)

Started by February 20, 2001 11:09 AM
3 comments, last by Thrump 23 years, 11 months ago
I have a VECTOR struct in C, and there are many times I call a function that takes a vector as input. If I want to put in an arbitrary value, I have to do something like this: VECTOR temp={0,0,5,1}; function1(temp); Now, what I want to do is something like this... function1({0,0,5,1}); I know C won''t do this, but I could do this... function1(v(0,0,5,1)); where v is a function that returns a pointer to a temporary VECTOR with the values 0,0,5,1. I''ve thought of 2 ways to do this. One would be to declare a static VECTOR inside v, and return that pointer. Another way would be to have a global temp VECTOR. Is there a better way to do this? Do you foresee any problems arising from either of these methods? Thx!
If you''re talking about putting a static data item inside a struct then I''m pretty sure you''re using C++ - in which case you can add a constructor to do what you want.

struct Vector3D
{
Vector3D():x(0),y(0),z(0){}
Vector3D(a,b,c):x(a),y(b),z(c){}
float x,y,z;
};
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
Advertisement
Doing this either with statics or globals will get you into trouble if you ever start doing multithreaded stuff. The problem being that if two threads ever called v() at the same time you''d get garbled output.

Plus it''s just unnecessary. You can just create your VECTOR return it directly. e.g.

VECTOR v(...){    VECTOR vec;    /* Initialize vec based on the parameters */    return vec;} 


-Mike
-Mike
Me bad! I said that VECTOR was a structure, but it''s only a typedef of float[4]. Sorry! Anon, you have the right idea I think, but will the fact that VECTOR vec is local to v be a problem? You''d be using a pointer to a variable that may not exist anymore. That''s why I thought to make it static. Sorry about the structure confusion Magmai. And, yes, multithreading will be a problem. But what if I''m only using it in one thread?
Actually Anon''s code does not return a ptr (to a local var), it returns an instance or (since VECTOR is typedef float VECTOR[4]) rather it will return a copy the whole array (thus create a temporary var to hold it), so it is quite valid.
If you declare the var static within v you''ll end up with trouble even if you only use it in one thread, consider the following code:

vector_add(v(1,2,3,4), v(5,6,7,8));

This is the perfect situation to migrate to C++.... Then this will work very nicely...

This topic is closed to new replies.

Advertisement