I am facing a problem concerning the dynamic allocation of structure, a linked chain containing a pointer to a structure to be more specific.
Code of the linked chain:
typedef struct Queue Queue;
struct Queue{
Real* elmt;
Queue* next;
Queue* prev;
};
So, this struct is circular, with next pointing to the next
Code of struct Real(which represents):
typedef struct Real Real;
struct Real{
int* nb; //int array containing the number
size_t size;
int neg; /*0=positive 1=negative*/
int com; /*-1 = no comma, otherwise integer indicating the position*/
};
So, as explained, I wish to dynamically allocate a queue containing several elements, so I created this function:
Queue* mallocQueueElmt(const Real* arg){
Queue* res=NULL;
res=mallocQueue();
res->elmt=NULL;
res->elmt=mallocReal(arg->size);
memmove(res->elmt->nb, arg->nb, sizeof(int)*arg->size);
res->elmt->com=arg->com;
res->elmt->neg=arg->neg;
res->next=res;
res->prev=res;
return res;
}
mallocReal()
just returns a pointer pointing at a Real structure containing a pointer(meaning the member nb
of the structure Real
) pointing at an array(dynamically allocated) of int with a size equal to arg->size
This works, I tested it with a function :
void printQueue(Queue* arg){
Queue* cur=NULL;
cur=arg->prev;
if(cur == arg->prev){;
printReal(cur->elmt);
printf(" ");
}
else
while(cur != arg){
cur=cur->next;
if(cur->elmt){
printReal(cur->elmt);
printf(" ");
}else{
printf("no element ");
}
}
}
But when I try to add an element, thanks to this function:
Queue* addElement(Queue* arg, const Real* arg1){
Queue* res=NULL;
res=mallocQueue();
res->elmt=NULL;
res->elmt=mallocReal(arg1->size);
memmove(res->elmt->nb, arg1->nb, sizeof(int)*arg1->size);
res->elmt->neg=arg1->neg;
res->elmt->com=arg1->com;
res->prev=arg->prev;
res->next=arg;
res->prev->next=res;
arg->prev=res;
res=arg;
return res;
}
and recall printQueue()
, then only the second element(so added with addElement()
) is
displayed, and nothing anormal happened, everything seemed to be running fine.
Thank you in advance for your help