Hello everyone
I want a struct in which one member is a pointer (arrProb) and the other is an integer to save the quantity of elements in the array.
Code:
typedef struct MODELOBJECT{
int numObjects;
double *arrProb; // TODO: Se tiene que hacer un realloc cada vez que se almacenar'a otro valor.
} ModelObject;
I make a malloc to define the size of data to store, but as you guys can see
And these are my problems
1. (See red line) How to allocate memory for the arrProb (although no apparent problems)
2. I have a compilation error in the function modelObject_printArrProb(ModelObject *modelObject)
Code:
$ gcc borrador1.c -o borrador1
borrador1.c: In function ‘modelObject_printArrProb’:
borrador1.c:11: error: request for member ‘numObjects’ in something not a structure or union
borrador1.c:13: error: request for member ‘numObjects’ in something not a structure or union
borrador1.c:14: error: request for member ‘arrProb’ in something not a structure or union
I want pass the structure as a pointer to another functions.
I hope guys can help me.
These is the complete code.
Code:
#include <stdio.h>
#include <malloc.h>
typedef struct MODELOBJECT{
int numObjects;
double *arrProb; // TODO: Se tiene que hacer un realloc cada vez que se almacenar'a otro valor.
} ModelObject;
void modelObject_printArrProb(ModelObject *modelObject){
printf("modelObject.numObjects = %d",modelObject.numObjects);
int i;
for(i=0;i<modelObject.numObjects;i++){
printf("arrProb[%d] = %f\n",i,modelObject.arrProb[i]);
}
}
int main(){
ModelObject modeloObjetos;
modeloObjetos.numObjects=5;
printf("sizeof %d\n",sizeof(modeloObjetos));
printf("modeloObjetos.numObjects = %d\n",modeloObjetos.numObjects);
printf("modeloObjetos.arrProb = %u\n",modeloObjetos.arrProb);
printf("sizeof modeloObjetos.arrProb %d\n",sizeof(modeloObjetos.arrProb));
modeloObjetos.arrProb = (double*)malloc(modeloObjetos.numObjects*sizeof(double *));
printf("after malloc\n");
printf("sizeof modeloObjetos.arrProb %d\n",sizeof(modeloObjetos.arrProb));
printf("modeloObjetos.arrProb = %u\n",modeloObjetos.arrProb);
int i;
int tope = modeloObjetos.numObjects;
tope = 10;
for(i=0;i<tope;i++){
modeloObjetos.arrProb[i]=rand();
printf("modelo.arrProb[%d] = %f\n",i,modeloObjetos.arrProb[i]);
}
printf("=======================================\n");
printf("sizeof modeloObjetos.arrProb %d\n",sizeof(modeloObjetos.arrProb));
printf("modeloObjetos.arrProb = %u\n",modeloObjetos.arrProb);
// modelObject_printArrProb(&modeloObjetos);
return 0;
}
Best Regards