0

I have written a program for insertion shot like following:

int _tmain(int argc, _TCHAR* argv[])
{
int arr[10] = {1,2,3,10,5,9,6,8,7,4};
int value;
cin >> value ;
int *ptr;
ptr = insertionshot(arr); //here Im passing whole array
BinarySearch(arr,value);
return 0;
}

int * insertionshot(int arr[])
{

//Changed after a hint (now, its fine)
int ar[10];
for(int i =0;i < 10; i++)
{
    ar[i] = arr[i];
}
 //Changed after a hint

int arrlength = sizeof(ar)/sizeof(ar[0]); //here array length is 1, it should be 10
for(int a = 1; a <= arrlength -1 ;a++)
{
    int b = a;
    while(b > 0 && ar[b] < ar[b-1])
    {
        int temp;
        temp = ar[b-1];
        ar[b-1] = ar[b];
        ar[b] = temp;
        b--;
    }
}
return ar; 
}

The problem is after passing the whole array to the function, my function definition only shows 1 element in array and also "arraylength" is giving 1.

bapi
  • 1,903
  • 10
  • 34
  • 59
  • 4
    There isn't any way to determine the size of an array unless it was defined locally. You will have to change your `insertionshot()` function to include another parameter, to indicate its size. – mah Apr 06 '14 at 14:52
  • 2
    `int * insertionshot(int arr[])` : `arr` is pointer to int. – BLUEPIXY Apr 06 '14 at 14:52
  • Please, don't use `TCHAR` and its ilk unless you are porting ancient Windows programs. – Deduplicator Apr 06 '14 at 15:09
  • @mah, thank you for this hint. Now I changed my code. – bapi Apr 06 '14 at 15:11

1 Answers1

1

int arr[] in a function formal parameter list is a syntax quirk, it is actually processed as int *arr. So the sizeof trick doesn't behave as you expect.

In C it is not possible to pass arrays by value; and furthermore, at runtime an array does not remember its length.

You could include the length information by passing a pointer to the whole array at compile time:

int * insertionshot(int (*arr)[10])

Of course, with this approach you can only ever pass an array of length 10. So if you intend to be able to pass arrays of differing length, you have to pass the length as another parameter.

Community
  • 1
  • 1
M.M
  • 138,810
  • 21
  • 208
  • 365