Ganesh
Ganesh

Reputation: 1

Passing array of structures to function in C

struct mystruct_type {
    int a;    
    int b;        
};      
typedef struct  mystruct_type mystruct;    

void function1    
{    
    mystruct place[N],*temp1,*temp2,*temp3;    
    temp1= malloc(sizeof(mystruct));    
    temp2= malloc(sizeof(mystruct));    

    temp1->a=3; temp1->b=4;        

    assign(temp2,temp1);      
    temp3=add(place,place+2);//Want to add mystruct[0]+mystruct[2],2+4,4+6....loop not   shown here       
}      

void assign (mystruct * m1,mystruct * m2)//Gives warning conflicting types for assign        
{       
    m1->a=m2->a;        
    m1->b=m2->b;     
}     

mystruct * add (mystruct * m1, mystruct * m2)//Error: Conflicting types for add     
{  
    complex * c;     
    c=malloc(sizeof(mystruct));       
    c->a=m1->a+m2->a;      
    c->b=m1->b+m2->b;       
    return c;    
}

Can anybody point whats the mistake?
Thanks....

Upvotes: 0

Views: 622

Answers (2)

user411313
user411313

Reputation: 3990

you should allocate memory simply and correct like:

typedef struct {
    int a;    
    int b;        
} mystruct;    

mystruct *initialize(size_t numElem)    
{    
    return calloc(numElem,sizeof(mystruct));    
}      

void assign (mystruct * m1,mystruct * m2)
{       
    *m1=*m2;     
}     

mystruct * add (mystruct * m1, mystruct * m2, mystruct *sum)
{  
    sum->a=m1->a+m2->a;      
    sum->b=m1->b+m2->b;       
    return sum;    
}

...
mystruct sum ={3,4} , *x = initialize(10);
assign( &x[0], &sum );
assign( &x[1], &x[0] );
add( &x[0], &x[1], &sum );
printf(" %d %d ", sum.a, sum.b );
...
free( x );

Upvotes: 0

Jesus Ramos
Jesus Ramos

Reputation: 23266

The conflicting type for add is because you return a pointer to a complex struct instead of a mystruct pointer.

As mentioned by Chris, you need to either place the functions add and assign above the function1 or declare them as

void assign(mystruct *, mystruct*);
mystruct *add(mystruct *, mystruct *);

at the top of your file.

Upvotes: 1

Related Questions