correct way to change values of c pointers

前端 未结 3 1659
走了就别回头了
走了就别回头了 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

    Your pointers are not initialized. You have two solutions:

    • use integers in main function (and eventually, although useless, make pointers point to them in the same function);
    • dynamically allocate memory for your pointer.

    Easiest code:

    #include 
    
    int main(void)
    {
        int arr[] = {1, 2, 9, 3, 58, 21, 4};
        int s, l;
        int size = 7;
        func(arr, &s, &l, size);
        printf("%d %d\n", l, s);
    } 
    

    In the current code, you don't need to make l and s point to the case of the array. So, as Dan F stated, you can just do integer's assignment.

    void func(int arr[], int *s, int *l, int n)
    {
        int i = 1;
        for(; i < n; i++){
            int temp = arr[i];
            int n = i;
            while( n > 0 && arr[n-1] > temp){
                arr[n] = arr[n-1];
                n--;
            }
            arr[n] = temp;
        }
        *l = arr[n-1];
        *s = arr[0];
        printf("%d %d\n", *l, *s);
    }
    

提交回复
热议问题