简体   繁体   English

将指向数组的指针作为函数的参数传递

[英]Passing pointers to an array as arguments to a function

I am trying to implement INSERTION SORT here in C , which I think I've done successfully. 我正在尝试在C实现INSERTION SORT ,我认为我已经成功完成了。 However, I am having problems in passing arrays as arguments . 但是,在passing arrays as arguments时遇到问题。

I want in place sorting, which means that the original array passed into the insertion_sort function should contain the elements in the sorted array itself. 我想要就地排序,这意味着传递给insertion_sort函数的原始数组应包含排序后的数组本身中的元素。

#include<stdio.h>

int * insertion_sort(int *a,int length)
{
    int j;
    for(j=1;j<length;j++)
    {
        int i,key=a[j];
        for(i=j-1;j>=0;j--)
        {
            if(a[i]<=key)
                break;
            a[i+1]=a[i];
        }  
        a[i+1]=key;
    }

    return *a;
}

int main(void)
{
    int a[]={10,12,7,6,9,8};
    insertion_sort(a,6);
    int i;    
    for(i=0; i<6; i++)
       printf("%d\n", a[i]);

    return 0;
}

EDIT Nothing gets printed in the output screen. 编辑在输出屏幕上什么都不会打印。 Help me find the bug here. 帮我在这里找到错误。 Thanks !! 谢谢 !!

1.You probably meant to use i in the inner loop: 1.您可能打算在内部循环中使用i

Change: 更改:

for(i=j-1;j>=0;j--) 
          ^^   ^^

to: 至:

for(i=j-1;i>=0;i--)

2.You don't have to return anything as the original array gets modified (which is just as well since you ignore the returned value). 2.当原始数组被修改时,您不必返回任何东西(由于您忽略了返回的值,所以也是如此)。

3.Array index starts from 0. Change outer loop to: for(j=0;j<length;j++) 3.数组索引从0开始。将外部循环更改为: for(j=0;j<length;j++)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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