简体   繁体   中英

C - parameter in function can't handle int if declared as int*

I want to use the C function called is_subsetOf() in two different ways:

Way 1: int* a and int* b are arrays with sizes >=2. Way 2: int* a has size >=2, but int* b is only size 1, which means b is an int.

How can I force C to be okay with int* b being of size 1? Or is this not possible in C? An int IS an array of size 1??

int* is_in(int *left_hand, int n_l, int *right_hand, int n_r) {
  int *get_bool;
  get_bool = malloc(sizeof(int)*n_l);

  for (int i=0; i<n_l; i++) {
    if (is_subsetOf(right_hand, n_r, *(left_hand+i), 1)) {
      *(get_bool+i) = 1;
    }
  }
  return (get_bool);
}

int desc(const void *a, const void *b) {
  return (*(int*)a - *(int*)b);
}

int is_subsetOf(int *a, int n_a, int *b, int n_b) {
  qsort(a, n_a, sizeof(int), desc);
  qsort(b, n_b, sizeof(int), desc);
  int v = includes(a, n_a, b, n_b);
  return(v);
}

Here are the messages I get from the compiler. It's just a warning, I know, but I'd like everything to be clean.

tmp.c: In function ‘is_in’:
tmp.c:73:47: warning: passing argument 3 of ‘is_subsetOf’ makes pointer 
from integer without a cast [-Wint-conversion]
     if (is_subsetOf(right_hand, n_r, *(left_hand+i), 1)) {
                                  ~~~~~~~~~^~~
tmp.c:37:39: note: expected ‘int *’ but argument is of type ‘int’
 int is_subsetOf(int *a, int n_a, int *b, int n_b) {

int* a and int* b are arrays with sizes >=2.

No, they are pointers and they don't have any size. You probably meant that you pass arrays through them, but they are not arrays. Know that there is a difference.

An int IS an array of size 1

No, int a[1]; is an array of size 1; int a; is just int . But arrays can decay into pointers to their first element and variables have addresses, so this is correct:

int a[1];
int b;
int* ptr1 = a;//Points to the a[0]
int* ptr2 = &b;

Both are now same type and can be used in the same way. Of course you don't know if the int is followed by any more ints in memory, that kind of checking is up to the programmer (usually by passing the length param as you do). The following is the code you are actually looking for:

is_subsetOf(right_hand, n_r, left_hand+i, 1)

Pointers can be incremented, left_hand+i will point to the i-th int after the int to which left_hand currently points to. Again, validity of such pointer is up to programmer.

The compiler warning is quite important here, because *(left_hand+i) is of type int and the compiler warns that it will treat is as int* . Essentially looking that the value of int as an address to memory. That's not at all what you want and it is an error .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM