Thread: Struct types and dynamic arrays

1. Struct types and dynamic arrays

Hi there,

I am using a struct whose elements may be arrays. I would like though, for these arrays to be dynamically allocatable when I declare them in the main code; how is it supposed to be done?

I wrap my code here; it's very simple, however, please let me know if there are more information that you need

Thank you in advance,
Best
S.M.

Code:
typedef struct Mesh{

float x; //x-coord of Vertex
float y; //y-coord of Vertex
float z; //z-coord of Vertex

} typeMesh

main
{

typeMesh COORDS [SIZE TO BE ALLOCATED] //This is where I'd like to allocate this dynamically.

/* What I would like to obtain is the COORDS array to be of SIZE_n that will be obtained as the output of another function that will be called only later in the code.

;

2. Code:
#include <stdio.h>
#include <stdlib.h>

typedef struct {

float x; //x-coord of Vertex
float y; //y-coord of Vertex
float z; //z-coord of Vertex

} Mesh;

int later_function () {
int size;
printf("How big? ");
scanf("%d",&size);
return size;
}

int main() {
int x,i;
Mesh *ray;
x=later_function();
ray=malloc(sizeof(Mesh)*x);
for (i=0;i<x;i++) {
ray[i].x=(float)i;
ray[i].y=(float)x-i;
ray[i].z=(float)(x-i)*0.5;
printf("Vertex %f %f %f\n",ray[i].x,ray[i].y,ray[i].z);
}
free(ray);
return 0;
}

3. Hello MK,

thank you very much for helping: I really appreciate it

All the best
S.M.

4. Originally Posted by simone.marras
thank you very much for helping: I really appreciate it
Happy to be helpful. b/t/w, I forgot to use an f here:
Code:
ray[i].z=(float)(x-i)*0.5f;
which doesn't matter much, but if you are using a lot of float vectors in eg, graphics stuff where optimization is a priority, without the "f" decimal numbers will get converted from a double (the default for decimals, I guess), which is one extra little thing for the processor to do. Using f and (float) ensures 0.5 is stored and accessed as a float, and the answer is stored and accessed as a float (without (float) it will be stored in the processor registers as a double and then converted to a float when placed into main memory).

Or So I Have Been Led To Believe.

5. Thank you very much for the hint;

I do programming for math applications and Im barely learning on this; it surely helps learning by these suggestions

One more question, do you do C++ as well? I am trying to do the same thing in my C++ version of the code, but not sure about how to deal with it if there is a CLASS in the between

Best
S.

6. Originally Posted by simone.marras
One more question, do you do C++ as well?
Me? No.

7. Thank you, Ill manage
S.

Popular pages Recent additions