Using malloc to store coordinates in C - c

I am writing a program and the part I am working on at the moment must take hundreds of triangles (that form a 3D shape) and store the coordinates of each triangle. For example, one triangle will have coordinates: (x1, y1, z1) (x2, y2, z2) (x3, y3, z3).
I think perhaps organising a struct in this way would be a start (but I am open to better ideas..!)
struct triangle {
double x1;
double y1;
double z1;
double x2;
double y2;
double z2;
double x3;
double y3;
double z3;
};
Essentially, I wish to be able to store each triangle's coordinates and then at another point in the program I would like to go back and delete some triangles and add some others to the 'list'.
I've been trying to do this for days now and any help would be much appreciated - it's driving me crazy...
Thanks in advance! Let me know if I can explain anything in better detail.

First, you might want to use a more user-friendly structures as:
struct coord_s {
double x;
double y;
double z;
}
struct triangle_s {
struct coord_s points[3];
}
Then, as far as malloc is concerned, you can allocate a pointer to a struct using malloc as such struct triangle_s *my_triangle = malloc(sizeof(struct triangle_s));
sizeof() will take care of calculating the size of the actual structure and send it to malloc()
Then you just need to choose what to use as storage depending on your use case

Related

How to get xz values as vector 3 dimensional vector

I have following struct declaration, which I use in my code. But when I needed to render only x and z coords, I need somehow to get only xz coordinates from a value like Point1.XZ:
union v3
{
struct
{
float x, y, z;
};
struct
{
v2 xy;
float Ignored0_;
};
struct
{
float x; //
float Ignored0_; // I Have problems with this
float z; //
};
struct
{
float Ignored1_;
v2 yz;
};
float E[3];
};
Is it possible to get only XZ coordinates as Vector2?
As Some programmer dude mentioned, for doing this I just needed simply to create a function or macro. I just used macro:
#define XZ(Vector) (V2(Vector.x, Vector.z))

Using malloc on structs / arrays in other files

UPDATE: The problem with the segmentation fault is not within this function as described below, it is within another function of the same program.
I'm trying to make a program that animates bouncing balls, however I am quite stuck and can't figure out what I am doing wrong. I believe I have isolated the problem to be within the function below. I have sort of figured out that it has something to do with the new-model statements.
Anyway, upon running the code I get segmentation fault and the values drawn by the function (in terms of triangles) are way out of where they should be. I should be getting values between 0 and 1600 but I end up with 94 million sometimes.
Any help is greatly appreciated!
object_t *create_object(SDL_Surface *surface, triangle_t *model, int numtriangles){
object_t *new=malloc(sizeof(object_t));
new->surface = surface;
new->model = malloc(sizeof(triangle_t)*numtriangles);
*new->model= *model;
new->numtriangles = numtriangles;
new->tx = surface->w/2;
new->ty = surface->h/2;
new->scale = 0.1;
new->rotation = 0.0;
return new;
}
NB! The triangle_t *model pointer points to an array which describes multiple triangles.
EDIT:
Including struct of object:
typedef struct object object_t;
struct object {
float scale; /* Object scale */
float rotation; /* Object rotation */
float tx, ty; /* Position on screen */
float speedx, speedy; /* Object speed in x and y direction */
unsigned int ttl; /* Time till object should be removed from screen */
int numtriangles; /* Number of triangles in model */
triangle_t *model; /* Model triangle array */
SDL_Surface *surface; /* SDL screen */
};
And struct of triangles:
typedef struct triangle triangle_t;
struct triangle {
/* Model coordinates, where each pair resemble a corner */
int x1, y1;
int x2, y2;
int x3, y3;
/* The color the triangle is to be filled with */
unsigned int fillcolor;
/* Scale factor, meaning 0.5 should half the size, 1 keep, and 2.0 double */
float scale;
/* The point (tx, ty) where the center of the teapot should be placed on-screen */
int tx, ty;
/* The degrees the triangle is supposed to be rotated at the current frame */
float rotation;
/*
* Bounding box of on-screen coordinates:
* rect.x - x-coordinate of the bounding box' top left corner
* rect.y - y-coordinate of the bounding box' top left corner
* rect.w - width of the bounding box
* rect.h - height of the bounding box
*/
SDL_Rect rect;
/* On-screen coordinates, where each pair resemble a corner */
int sx1, sy1;
int sx2, sy2;
int sx3, sy3;
};
This line is copying only the first triangle:
*new->model = *model;
From the point of view of your function model is only a pointer to an object. The compiler doesn't know it points to an array of triangles, hence we need to pass the number of triangles in there as an argument.
Replace it for:
memcpy( new->model, model, sizeof(triangle_t)*numtriangles);
Additional comments:
Remember to free the model when freeing the object
Replace new for something else like newObj if you ever consider to compile this with a c++ compiler
More info:
https://linux.die.net/man/3/memcpy
https://en.cppreference.com/w/c/string/byte/memcpy
[EDIT]
Regarding to the segmentation fault: your function is correct now and it is not causing SEGFAULT unless you are running out of memory, what is very unlikely. Anyway, if you are running out of memory and getting a SEGFAULT in that function then the problem is either:
you are not deallocating memory correctly somewhere else and then you have a memory leak making you run out of memory improperly.
your platform needs more memory what, despite unlikely, is possible especially if it is a limited embedded platform
Post another question with the backtrace of the segfault.

Is there a way to define behavior of struct arithmetic?

I have a struct vec:
struct vec {
float x, y, z;
}
And a method to do arithmetic on two vectors, in this case subtraction:
vec* sub(vec* a, vec* b) {
struct vec* new = (vec*)malloc(sizeof(struct vec));
new->x = a->x - b->x;
new->y = a->y - b->y;
new->z = a->z - b->z;
return new;
}
Behavior of arithmetic with integers, floats, etc is simple:
int - int = int
But is undefined for vec:
vec - vec = compiler errors
Is there a way to define behavior of operands on structs? Say I just want to type new = a - b, is there a way to configure it such that that line does the function sub?
This is what C++ gives you. In C, you stick with calling sub.
Another issue is the dynamic allocation, it can get clunky and means you can't work with stack varibles as easily. Couple of solutions to that, move the allocation out of the subtract
if we typedef the vec :-
typedef struct { float x, y, z;} vec;
then...
vec* subtract(vec* l, vec *r, vec *result);
you can them build a subtract ontop of this one that also mallocs if you like, but this way the subtract will work with either dynamic or stack based variables.
or by value
vec subtract(vec l, vec r);
by value is probably best for your small struct, but, it's up to you.

Struct function on C

I have got a question i am working on and this is as follows (with a bunch of constants that aren't relevant)
Use a struct to represent an (x, y) coordinate. A second struct must then be used to represent the sound source — its (x, y) coordinate and the W value. You will also need to declare an appropriate array of struct variables. You may assume that not more the 100 sound sources will be involved in the plant/site being analysed.
This is what i got so far;
struct point
{
double x, y;
};
/* for sound sources */
struct source
{
struct point location;
float power;
};
Is there anyway to rewrite this in a different way? or a 'more correct' way?
There is nothing wrong with what you have written, although it doesn't include the last part of your spec (the array).
There are many other ways to do this; how relatively "correct " they are to this one depends on what criteria you have for comparing them, none of which you have provided. Besides, that kind of discussion is better suited for a code review, and hence a question for a different site.
That looks fine, but there is another way to write this that I tend to prefer:
typedef struct tagPoint
{
double x, y;
} point, *pPoint;
typedef struct tagSource
{
point location;
float power;
} source, *pSource;
I find this method a bit cleaner, as you do not need to write out the struct each time you use the structure.

Warning when using anonymous structures in a 4D matrix type

I'm trying to define a 4-d matrix type in C (for use in the iOS/ObjC environment) that is encapsulated (so not a bare array), and that can be accessed using indexed values or via named struct members. This is my attempt:
typedef union {
float m[16];
struct {
struct {
float x;
float y;
float z;
float w;
} x;
struct {
float x;
float y;
float z;
float w;
} y;
struct {
float x;
float y;
float z;
float w;
} z;
struct {
float x;
float y;
float z;
float w;
} w;
}; // warning here "Declaration does not declare anything"
} Matrix4;
This works, but I get a warning due to the anonymous (unnamed) struct. I obviously don't want to name that container struct as it only serves to hold the four inner structs.
This page implies that I should be able to do this?
http://gcc.gnu.org/onlinedocs/gcc/Unnamed-Fields.html#Unnamed-Fields
It seems to actually work, so is this wrong, or if not, how should I get rid of the warning?
I'm using LLVM GCC 4.2.
Thanks for any insight or suggestions.
Anonymous structs and unions are now allowed (as of C11). Your worries will eventually go away as you migrate to a newer compiler. In GCC, add -std=c1x.

Resources