Search code examples
cflexible-array-member

How to send array by value to function in c?


I tried something like :

typedef struct vec{
     int sz;
     int v[];
} ff;

int sum(struct vec z){
    int o=0,i;
    for(i=0;i<z.sz;i++)
        o+=z.v[i];
    return o;
}

int main(){
    int test[]={10,1,2,3,4,5,6,7,8,9,10};
    return sum((struct vec)test);
}

But this example code can't compile. How to send array by value (not ref throw pointer) to function?


Solution

  • In your example, you will need to specify the exact size of the array in the definition of struct vec, for example int v[10]. Also your initialization can be written better. Try this:

    #define MAX_SIZE 50
    struct vec {
       int sz;
       int v[MAX_SIZE];
    };
    
    int sum(struct vec z){
      int i, o;
      o = 0;
      for(i=0; i<z.sz; i++) o += z.v[i];
      return o;
    }
    
    int main(){
      struct vec test = {10, {1,2,3,4,5,6,7,8,9,10}};
      return sum(test);
    }