correct way to change values of c pointers

前端 未结 3 1658
走了就别回头了
走了就别回头了 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-10 00:06

    You need to pass the address of the pointer variables if you want to change what they are pointing at, otherwise a copy of the pointer variable is being changed inside the function (and is why it is correct within the function):

    void func(int arr[], int** s, int** l, int n){
        /* snip */
    
        *l = &arr[n-1];
        *s = &arr[0];
    }
    
    func(arr, &s, &l, size);
    

    This would leave s and l pointing to elements of the array arr. If you just wanted the values of integers then the alternative would be to define int variables in main() and pass their addresses to func() and copy the relevent values from the array:

    void func(int arr[], int* s, int* l, int n){
        /* snip */
    
        *l = arr[n-1];
        *s = arr[0];
    }
    
    int s, l;
    func(arr, &s, &l, size);
    

    See this question from the C FAQ.

提交回复
热议问题