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.
问题是在将整个数组传递给函数之后,我的函数定义只在数组中显示1个元素,而“arraylength”则给出1。
1 个解决方案
#1
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.
函数形式参数列表中的int arr []是一个语法怪癖,它实际上被处理为int * arr。所以sizeof技巧不会像你期望的那样表现。
In C it is not possible to pass arrays by value; and furthermore, at runtime an array does not remember its length.
在C中,不能按值传递数组;此外,在运行时,数组不记得它的长度。
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.
当然,使用这种方法,您只能传递长度为10的数组。因此,如果您打算能够传递不同长度的数组,则必须将长度作为另一个参数传递。
#1
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.
函数形式参数列表中的int arr []是一个语法怪癖,它实际上被处理为int * arr。所以sizeof技巧不会像你期望的那样表现。
In C it is not possible to pass arrays by value; and furthermore, at runtime an array does not remember its length.
在C中,不能按值传递数组;此外,在运行时,数组不记得它的长度。
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.
当然,使用这种方法,您只能传递长度为10的数组。因此,如果您打算能够传递不同长度的数组,则必须将长度作为另一个参数传递。