简体   繁体   English

为什么我必须返回指针?

[英]Why do I have to return pointer?

I tried to write an function that sorts arrays using pointers. 我试图编写一个使用指针对数组进行排序的函数。 My p pointer points to x array but why should I return x as a pointer? 我的p指针指向x数组,但是为什么我应该返回x作为指针呢?

    #include <stdio.h>
    int sort(int x[], int n){
    int *p,k;
    p=x;
    for(int i=0; i<n-1; i++){
        for(int l=i+1; l<n; l++){
            if(*(p+i)>*(p+l)){
                k=*(p+i);
                *(p+i)=*(p+l);
                *(p+l)=k;
            }
        }
    }
    return *x;
}
int main(){
    int n;
    scanf("%d", &n);
    int a[n];
    for(int i=0; i<n; i++){
        scanf("%d",&a[i]);
    }
    sort(a,n);
    for(int i=0; i<n; i++){
        printf("%d ",a[i]);
    }
    return 0;
}

your function returns an int (value), not a pointer. 您的函数返回一个int (值),而不是一个指针。 your implementation ( return *x; ) returns the first element of parameter x[] by value. 您的实现( return *x; )按值返回参数x[]的第一个元素。

why should I return x as a pointer? 为什么要返回x作为指针?

what is the return value supposed to indicate? 返回值应该指示什么? it's not clear why you would return anything in this scenario. 目前尚不清楚在这种情况下为什么要返回任何东西。 until you can answer that, void would be better. 直到您能回答这个问题, void会更好。

The short answer to why you “have to” return a pointer is that you clearly don't have to return anything. 为什么要“必须”返回指针的简短答案是,您显然不必返回任何内容。 You are not returning pointer (but an int ) and you are not using the returned value for anything. 不是在返回指针(而是int ),并且也没有将返回值用于任何东西。 You can change function's return type to void and remove the line with return and it will work just as well. 您可以将函数的return类型更改为void并删除带有return的行,它也将正常工作。

The reason why it works without returning anything is that you are passing a pointer to the array a as argument to sort and then modifying the array — known as x inside that function – in place. 为什么它不返回任何东西的原因是要传递一个指向数组a作为参数sort ,然后修改阵列-被称为x该函数内部-到位。 So there is only one array, and thus you don't have to return another one, or a pointer thereto, for the changes to be visible in main . 因此只有一个数组,因此您不必返回另一个数组或指向该数组的指针,即可在main看到更改。

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

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