I've recently started using structures, but I am having problems in allocating the structure dynamically. In the code below if i allocate the structure in the main program it works fine, and i get the expected output. However if i use the function rper below to increase the size of the structure i get totally wrong results. Am i passing the structure wrong to the function? From what i understand I am just passing the pointer and realloc just chages the pointer, which then should be returned to the main function. But it seems that the allocation of elem, poi ,sign messes something up. Thanks for your help

Cezary

Program:

#include

typedef struct peri{

int no;

int *elem;

int *poi;

int *sign;

int reduced;

int type;

} peri ;

void rper(int size,peri *per);

int main (int argc, char *argv[]){

int nnods=10,i;

peri *per;

per= (peri *) malloc((2)*sizeof(peri));

per[1].no=2;

for(i=1;i<=nnods;i++){

rper(i,per);

/* per=realloc(per,(i+1)*sizeof(peri));

per[i].elem=(int*)malloc(2*sizeof(int));

per[i].poi=(int*)malloc(2*sizeof(int));

per[i].sign=(int*)malloc(2*sizeof(int));

per[i].no=i;*/

printf(" for i %d per.no is %d\n",i,per[i].no);

}

return;

}

void rper(int size,peri *per){

per=realloc(per,(size+1)*sizeof(peri));

per[size].elem=(int*)malloc(2*sizeof(int));

per[size].poi=(int*)malloc(2*sizeof(int));

per[size].sign=(int*)malloc(2*sizeof(int));

per[size].no=size;

}

Results if realloc in main:

for i 1 per.no is 1

for i 2 per.no is 2

for i 3 per.no is 3

for i 4 per.no is 4

for i 5 per.no is 5

for i 6 per.no is 6

for i 7 per.no is 7

for i 8 per.no is 8

for i 9 per.no is 9

for i 10 per.no is 10

Results if realloc in function:

for i 1 per.no is 1

for i 2 per.no is 0

for i 3 per.no is 0

for i 4 per.no is 0

for i 5 per.no is 0

for i 6 per.no is 0

for i 7 per.no is 0

for i 8 per.no is 0

for i 9 per.no is 0

for i 10 per.no is 0