I declared a few geometric figures types such as:
typedef struct s_sphere{
t_tuple origin;
double radius;
} t_sphere;
typedef struct s_cylinder{
t_tuple origin;
double height;
double radius;
} t_cylinder;
typedef struct s_triangle{
t_tuple A;
t_tuple B;
t_tuple C;
} t_triangle;
etc...
Now, I would like to declare an intersection type which will contain two doubles and a geometric figure. I will then store all my intersections in a chained list:
// I do not know what type to give to geometric_figure
typedef struct s_intersection{
double t1;
double t2;
// what_type geometric_figure;
} t_intersection;
typedef struct s_intersection_list{
t_intersection intersection;
struct s_intersection_list *next;
} t_intersection_list;
I could use void* geometric_figure but I would like to avoid the most mallocs possible.
Is there a handy way of getting where I want without allocating geometric_object ?
type which will contain two doubles and a geometric figure.
Consider union with an identifier.
typedef struct s_intersection{
double t1;
double t2;
int id; // some id to know what type follows
union {
t_sphere sph;
t_cylinder cyl;
t_triangle tri;
} u;
} t_intersection;
If t_intersection is to be allocated, consider a flexible member array to right size the allocation.
typedef struct s_intersection{
double t1;
double t2;
int id; // some id to know what type follows
union {
t_sphere sph;
t_cylinder cyl;
t_triangle tri;
} u[]; // FAM
} t_intersection;
Example: allocate a triangle.
t_intersection *p = malloc(sizeof *p + sizeof p->u[0].tri);
Related
I have a struct with several members and one of them is the same struct itself. What I want to do is have a pointer to a struct related to that same struct but is of the same type. The compiler does not recognize the type when reading the struct members since it is still to be defined. Is there any alternative way to do what I want to happen?
typedef struct _panels
{
int id;
// Dimensions
double length;
double height;
// Global coordinates of origin of LCS
double origX;
double origY;
double origZ;
// Orientation of local x-axis wrt global X-axis
double angle;
// Panel reinforcement
int nReinforcement;
double *xReinf; // arbitrary spacing
double sx; // fixed spacing
double xReinf0; // x-coordinate of first rebar
// CHB unit
CHBUnit *chb;
// Openings
int nOpenings;
CHBOpening *openings;
// Pointer to adjacent panels
CHBPanel * left; int leftPanelID;
CHBPanel * right; int rightPanelID;
}CHBPanel;
You should use the defined (incomplete in the definition of the structure) type struct _panels instead of CHBPanel, which is not defined yet, to declare pointers to the structure itself.
The last part
CHBPanel * left; int leftPanelID;
CHBPanel * right; int rightPanelID;
should be
struct _panels * left; int leftPanelID;
struct _panels * right; int rightPanelID;
Alternative way: You can do the typedef before the declaration of the structure.
typedef struct _panels CHBPanel;
struct _panels
{
int id;
/* snipped */
// Pointer to adjacent panels
CHBPanel * left; int leftPanelID;
CHBPanel * right; int rightPanelID;
};
I am currently working with a C program that uses structs composed of xyz coordinates, but sometimes these coordinate may refer to vectors (Force/velocity type, not the data structure) while at other times it may be referring to position. I know its possible to simply use one struct for all of these different conditions since they all use mostly the same data type (float), but to simply keep my math better organized (plus variable and struct names) and keep things from getting mixed up, is there a way to define a base struct that defines itself as having three floats, be inherited by another struct that more specifically defines what the struct is supposed to be (such as position instead of velocity, etc. etc.)? I know C is not OOP, but it seems like it could be possible to do this Here is what the base struct would be like:
struct ThreeDCartesianData
{
float x;
float y;
float z;
};
A more specific struct would inherit from that and perhaps define extra variables, or use different names for the variables. There will be multiple position structs being used, but I think only one velocity struct for each set of data. I have seen similar questions to this, but they all seem to be referring to a higher level language (C++, C#, etc. etc.)
You can use a union for this. Your main struct would contain a union of the "derived" structs as well as a "flag" field telling you which member of the union is valid:
enum { DERIVED11, DERIVED2, DERIVED3 };
struct derived1 { int x1; };
struct derived2 { char x2; };
struct derived3 { float x3; };
struct ThreeDCartesianData
{
float x;
float y;
float z;
int derivedType;
union {
struct derived1 d1;
struct derived2 d2;
struct derived3 d3;
} derived;
};
Then you can use them like this:
struct ThreeDCartesianData data1;
data1.x=0;
data1.y=0;
data1.z=0;
data1.derivedType = DERIVED1;
data1.derived.d1.x1 = 4;
You could alternately define them like this:
struct common
{
int type;
float x;
float y;
float z;
};
struct derived1
{
int type;
float x;
float y;
float z;
int x1;
};
struct derived2
{
int type;
float x;
float y;
float z;
char x2;
};
struct derived3
{
int type;
float x;
float y;
float z;
float x3;
};
union ThreeDCartesianData {
struct common c;
struct derived1 d1;
struct derived2 d2;
struct derived3 d3;
};
And use them like this:
union ThreeDCartesianData data1;
data1.c.type=DERIVED1;
data1.d1.x=0;
data1.d1.y=0;
data1.d1.z=0;
data1.d1.x1 = 4;
If all the structs in a union have an initial list elements of the same type in the same order, the standard allows you to access those fields from any of the sub-structs safely.
What about using typedefs?
typedef struct general3d {
float x;
float y;
float z;
} general3d_t;
typedef general3d position;
typedef general3d velocity;
This way, when you come across something that's a velocity type, you encode that into the variable type, but under the hood, it's still just 3 points, x, y, z. Then, readers of the code will know you're talking about a velocity and not a position. If you want to get really crazy with it, you hide general3d away in some implementation file, so a user can never instantiate a general3d on their own, since they should be using either position or velocity as the situation requires; this may or may not be reasonable for your task at hand/worth the extra effort.
EDIT: I'm not positive about variable-renaming or about adding more variables directly to the same struct, but I would start to head in the direction of a different design at that point.
On the one hand, if you have two structs that have the same underlying types but require different names, you probably just have two separate structs. For example:
struct point3d {
float x;
float y;
float z;
};
struct person {
float age;
float weight;
float salary;
};
Yes, those are both 3 floats, but their understanding is very different, and they should be able to vary on their own if one or the other changes. Perhaps I want to add a name field to the person, but there's no reasonable analogue for a char * on point3d. Just define them separately if they mean different things.
As for adding more variables, that sounds like structs that contain other structs:
struct point3d {
float x;
float y;
float z;
};
struct person {
point3d position;
float age;
float weight;
float salary;
};
// access like:
person.position.x;
I've done this sort of thing before. I embed a copy of the base type at the front of the derived type struct. This more closely mimics what c++ might do. Here are two methods I've used.
Using simple type:
#define XYZDEF \
int type; \
float x; \
float y; \
float z
// base type
struct xyzdata {
XYZDEF;
};
// derived type 1
struct vector {
XYZDEF;
int vector_info;
...
};
// derived type 2
struct position {
XYZDEF;
int position_info;
...
};
#define BASEOF(_ptr) \
((struct xyzdata *) (_ptr))
// vector_rotate -- rotate a vector
void
vector_rotate(vector *ptr)
{
}
// position_rotate -- rotate a position
void
position_rotate(position *ptr)
{
}
// xyzrotate -- rotate
void
xyzrotate(xyzdata *ptr)
{
switch (ptr->type) {
case TYPE_POSITION:
vector_rotate((vector *) ptr);
break;
case TYPE_VECTOR:
position_rotate((position *) ptr);
break;
}
}
Using a virtual function table pointer:
#define XYZDEF \
int type; \
vtbl *vtbl; \
float x; \
float y; \
float z
// forward definitions
struct xyzdata;
struct vector;
struct position;
// virtual function table
struct vtbl {
void (*rotate)(struct xyzdata *);
};
// base type
struct xyzdata {
XYZDEF;
};
// derived type 1
struct vector {
XYZDEF;
int vector_info;
...
};
// derived type 2
struct position {
XYZDEF;
int position_info;
...
};
#define BASEOF(_ptr) \
((struct xyzdata *) (_ptr))
// vector_rotate -- rotate a vector
void
vector_rotate(struct xyzdata *ptr)
{
struct vector *vec = (void *) ptr;
...
}
// position_rotate -- rotate a position
void
position_rotate(struct xyzdata *ptr)
{
struct position *pos = (void *) ptr;
...
}
// xyzrotate -- rotate
void
xyzrotate(xyzdata *ptr)
{
ptr->vtbl->rotate(ptr);
}
I'm trying to do this:
typedef struct {
float x;
float y;
} coords;
struct coords texCoordinates[] = { {420, 120}, {420, 180}};
But the compiler won't let me. : ( What's wrong with this declaration? Thanks for your help!
Either do:
typedef struct {
float x;
float y;
} coords;
coords texCoordinates[] = { {420, 120}, {420, 180}};
OR
struct coords {
float x;
float y;
};
struct coords texCoordinates[] = { {420, 120}, {420, 180}};
In C, struct names reside in a different name space than typedefs.
Of course you can also use typedef struct coords { float x; float y; } coords; and use either struct coords or coords. In this case it won't matter what you choose, but for self-referencing structures you need a struct name:
struct list_node {
struct list_node* next; // reference this structure type - need struct name
void * val;
};
I need to reference a struct that's not yet defined because the struct actually conatins the typedef'd function prototype.
For example,
typedef int (MyCallbackFunction)(X * x, void * ctx);
typedef struct CallbackData {
MyCallbackFunction * callback;
void * ctx;
} CallbackData;
typedef struct X {
char a;
int b;
int c;
double d;
CallbackData e;
} X;
What's the valid way to actually write this code/header ?
Just forward declare the relevant types - and you can make the function pointer part of the typedef:
struct X_;
typedef int (*MyCallbackFunction)(struct X_ * x, void * ctx);
typedef struct CallbackData_ {
MyCallbackFunction callback;
void * ctx;
} CallbackData;
typedef struct X_ {
char a;
int b;
int c;
double d;
CallbackData e;
} X;
Just forward declare your typedefs
typedef struct X X;
typedef struct CallbackData CallbackData;
and then declare the structs later.
Yes, you can forward declare the struct and use it in the declaration of MyCallbackFunction where you don't need it to be a complete type.
struct X;
typedef int (MyCallbackFunction)(struct X * x, void * ctx);
Can I do something like this? I would like to use data types instead of constants in my enum type_t.
typedef struct {
char id;
long data;
} type1_t;
typedef struct {
char id;
long data;
float moredata;
} type2_t;
typedef enum {
type1_t, type2_t
} type_t;
typedef struct {
type_t type;
char* something;
} midas;
midas obj1;
obj1.type = type1_t;
obj1.type.id = 0;
obj1.type.data = 123;
midas obj2;
obj2.type = type2_t;
obj2.type.id = 3;
obj2.type.data = 456;
obj2.type.moredata = 3.14;
In the example the type variable of the midas struct should then refer to type1_t or type2_t. So if I set the type to type2_t, the size of it should be bigger than when I set type1_t.
No, you can't do that. If you were using C++, you could use templates to achieve this. But there is no "type enum" mechanism in C.
You could consider a union:
typedef enum {
type1, type2
} type_t;
typedef struct {
type_t typecode;
union {
type1_t type1value;
type2_t type2value;
};
char* something;
} midas;
This will cause midas.type1value and midas.type2value to occupy the same memory space. The amount of memory taken for the union will be equal to the amount of memory required to store the largest data type it contains.
You would then have to look at midas.typecode and consider which union member to use. If you use the wrong one you will wind up with invalid data and this may lead to program crashes, so be careful.
No. The usual way to do something like this in C is with a union:
typedef enum { TYPE1, TYPE2 } type_t;
typedef struct {
type_t type;
union
{
type1_1 t1;
type2_t t2;
} u;
} midas;
midas obj1;
obj1.type = TYPE1;
obj1.u.t1.id = 0;
obj1.u.t1.data = 123;
midas obj2;
obj2.type = TYPE2;
obj2.u.t2.id = 3;
obj2.u.t2.data = 456;
obj2.u.t2.moredata = 31.14;
I think you are looking for union
No, you can't do that. enums are more or less equivalent to ints.
You can do this sort of thing was a union, e.g.:
typedef struct
{
int a;
float b;
} type1_t;
typedef struct
{
char c;
long d;
} type2_t;
typedef union
{
type1_t t1;
type2_t t2;
} myUnion_t;
...
myUnion_t u;
u.t1.a = 3;
u.t1.b = 2.7f;
That does not work. The closest thing would be to use a void* to your structure.