correct way to change values of c pointers

前端 未结 3 1656
走了就别回头了
走了就别回头了 2021-02-09 23:43

Sorry, another C pointer question.. I have a function func() that sorts an array, then get the largest and smallest integers. I\'m trying to put them inside pointer variables in

3条回答
  •  说谎
    说谎 (楼主)
    2021-02-09 23:48

    When you pass a pointer as an argument to a function in C, a copy of the pointer is made. Thus, changing the value of the pointer has no effect outside of that function. However, changing the value at the memory referenced by the pointer will take effect everywhere, as you want. In your case, you would need to do this:

    void func(int arr[], int *s, int *l, int n){
        // sorting code..
        // l = &arr[n-1]; WRONG - these change the value of the pointer,
        //s = &arr[0];\   without changing the value of the memory they reference
    
        *l = arr[n-1]; // CORRECT - changes the value at the referenced memory
        *s = arr[0];
        printf("%d %d\n",*l,*s);
    }
    

    Of course, the way you're using the pointers in main is also incorrect; they're uninitialized and likely to cause a segmentation fault. Since there appears to be no reason to use actual int* variables over ordinary int variables there, we can take another approach to passing them "by reference":

    int main(void){
        int arr[] = {1,2,9,3,58,21,4};
        // int *s, *l; WRONG - we don't need pointers, we need to pass regular ints
        int s, l;
        int size = 7;
        // Get the address of our variables with the address-of (&) operator
        // This effectively creates int* variables out of our int variables
        func(arr, &s, &l,size);
        printf("%d %d\n",*l,*s);
    } 
    

    Note that the term "by reference" here is not correct in the true sense of the phrase, since you are still receiving a copy of the address associated with the variable. Most languages provide a true by-reference faculty by removing this distinction and only allowing you access to the variable and its value, with the copying somewhat out of sight of the programmer. You can think of this as being "by reference with respect to l and s inside main", in the sense that their values can change due to the called function.

提交回复
热议问题