Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing an array in call by value

Tags:

c

I have a problem calling a function by passing the value,here is the test code

#include <stdio.h>

void sample(int b[3][2])
{
  int t;
  for(t=0;t<3;t++)
  {
    printf("value is =%d\n",b[t][0]);
  }
}

int main()
{

  int d[3][2]={(2,3),(4,2),(5,2)};

  sample(d[3][2]);
}

I get an error saying the reference type should be (*)[2] and not 'int'. What is the right way?

like image 647
james Avatar asked Dec 20 '25 09:12

james


1 Answers

You cannot pass an array by value in C: arrays are passed by address. If you want to pass an array by value, wrap it in a struct:

struct with_array {
    int b[3][2];
};
void sample(struct with_array s) {
    ...
}
int main() {
    struct with_array arg = {.b = {{2,3},{4,2} ,{5,2}}};
    sample(arg);
}

P.S. If you do not need to pass by value, your approach can be fixed, too. You need to follow the right syntax on initialization, and pass the whole array to sample, rather than accessing one of its elements (which is also beyond the bounds of the array).

like image 93
Sergey Kalinichenko Avatar answered Dec 23 '25 04:12

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!