Search code examples
cfunctionstructargument-passing

How to pass structures to a function in C


I wrote a C code which is formed by these files: main.c, kernel.c. Here are the files:

main.c:

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

typedef struct{
  float x;
  float y;
  float z;
} vect_xyz;

vect_xyz *coll_vcm1;

#include "kernel.c"
//==============================================================
int main(void){

int Np=10, i;   
float xx = 1;
coll_vcm1=(vect_xyz*)malloc(Np*sizeof(vect_xyz));

for(i=0;i<Np;i++){
  coll_vcm1[i].x = xx;
  coll_vcm1[i].y = 2*xx;
  coll_vcm1[i].z = 3*xx;
  xx = xx + 1;
}

for(i=0;i<Np;i++){
  collisione(coll_vcm1[i].x,i);
}

return 0;
}

kernel.c

void collisione(vect_xyz *coll_vcm1,int i){ 
  printf("coll_vcm1[%d].x=%f\n",i,coll_vcm1[i].x);
}

Here is the make file:

CC=gcc
CFLAGS=-Wall
OBJS = main.o 

all: eseguibile

eseguibile: $(OBJS)
   $(CC) $(CFLAGS) $(OBJS) -o eseguibile -lm

main.o: main.c kernel.c
   $(CC) -c $(CFLAGS) main.c

clean:
  rm -rf *.o eseguibile

(watch out for the tabs). When I run it by typing make I get this error message:

main.c: In function ‘main’:
main.c:30:7: error: incompatible type for argument 1 of ‘collisione’
   collisione(coll_vcm1[i].x,i);
   ^
In file included from main.c:14:0:
kernel.c:1:6: note: expected ‘struct vect_xyz *’ but argument is of type ‘float’
void collisione(vect_xyz *coll_vcm1,int i){ 
  ^
make: *** [main.o] Error 1

Of course the mistake occurs when I call the function collisione() but I don't understand why. The other thing that I suppose to be wrong is in the kernel.c file; as a matter of fact I believe that writing vect_xyz *coll_vcm1 is wrong because I am not specifying the index i.

So here is my question: - What should I write in the kernel.c file in order to print the values of structure everytime in the for loop?

PS: I want to keep the loop

for(i=0;i<Np;i++){
  collisione(coll_vcm1[i].x,i);
}

outside of the kernel.c file.


Solution

  • You should change this

    collisione(coll_vcm1[i].x,i);
    

    to

    collisione(coll_vcm1, i);
    

    you where passing the x field at position i in the array, instead of the pointer to the array coll_vcm1

    Also, note that casting the return value from malloc() makes you among other things, repeat yourself.

    coll_vcm1=(vect_xyz*)malloc(Np*sizeof(vect_xyz));
    

    could just be

    coll_vcm1 = malloc(Np * sizeof(vect_xyz));
    

    and what you actually should do, is check the return value, on error malloc() returns NULL, so

    coll_vcm1 = malloc(Np * sizeof(vect_xyz));
    if (coll_vcm1 == NULL)
        tragedy_cannotAllocateMemory_DoNot_Continue();
    

    and finally take your time to format your code, so others and you can read it and understand it.