BrewerHimself
BrewerHimself

Reputation: 123

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);
 }

Upvotes: 5

Views: 334

Answers (1)

reuben
reuben

Reputation: 3370

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.

Upvotes: 10

Related Questions