Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Full array not being passed in C

I'm working on an insertion sort and my array in main() seems to only be partially passed to sort(). The snippet below shows that test in main() has the value {2, 1, 3, 1, 2}, but arr in sort() has the value {2, 1}. What's going on here?

 #include <stdio.h>

 int sort(int* arr) {
      int i = 0;
      int j, key;
      int count = 0;

      printf("Inside sort(): ");
      for (j = 0; j < sizeof(arr)/sizeof(int); ++j)
           printf("%d ", arr[j]);
      printf("\n");

      for (j = 1; i < sizeof(arr)/sizeof(int); ++j) {
           key = arr[j];
           i = j - 1;
           while (i >= 0 && arr[i] > key) {
                arr[i + 1] = arr[i];
                --i;
                ++count;
           }
           arr[i + 1] = key;
      }
      return count;
 }

 int main(int argc, char* argv) {
      int test[] = {2, 1, 3, 1, 2};
      int i = 0;
      printf("Inside main(): ");
      for (i = 0; i < sizeof(test)/sizeof(int); ++i)
           printf("%d ", test[i]);
      printf("\n");
      int count = sort(test);
 }
like image 786
BrewerHimself Avatar asked Jul 04 '12 23:07

BrewerHimself


1 Answers

The idiom sizeof(arr)/sizeof(int) only works for statically-allocated arrays, and only within the scope that defines them.

In other words, you can use it for arrays like:

int foo[32];

...in the scope in which they're defined. But not elsewhere, and not for arrays simply passed as pointers. For other cases, you'll need to pass along extra information indicating the expected number of elements in the array.

like image 101
reuben Avatar answered Sep 25 '22 20:09

reuben