我正在所有函数中传递count指针,但它的值不会更改并保持0

int binarysearch(int a[],int l,int r,int k,int *count)
{

    int m = (r+l)/2;
    if (r > l)
    {
        if (a[m] > k){
            *count++;
         return binarysearch(a,l,m-1,k,count);
        }
        if (a[m] < k)
        {
            *count++;
            return binarysearch(a,m+1,r,k,count);
        }
        if (a[m] == k)
        {
            *count++;
            return m;
        }
    }
    if (r <= l)
    {
        *count++;
        if (k>a[l]) return l+1;
        else return l;
    }

}


void insertati (int a[],int i,int *count)
{

    int t = binarysearch(a,0,i-1,a[i],count);
    int y = a[i],j = i-1;
    while (j >= t)
        {
            a[j+1] = a[j];
            j--;
        }
    a[j+1] = y;
}

void insetionsort(int a[],int n,int *count)
{

    for (int i = 1; i < n; ++i)
    {
        insertati(a,i,count);
    }
}

int main()
{

    int n,count =0;
    scanf("%d",&n);
    int arr[n];
    for (int i = 0; i <n; ++i)
    {
        scanf("%d",&arr[i]);
    }
    insetionsort(arr,n,&count);
    printf("%d\n",count);
    for (int i = 0; i <n; ++i)
    {
        printf("%d ",arr[i]);
    }


    return 0;
}

最佳答案

用圆括号将解引用括起来:

int binarysearch(int a[],int l,int r,int k,int *count) {
    int m = (r+l)/2;
    if (r > l)
    {
        if (a[m] > k){
            (*count)++;
         return binarysearch(a,l,m-1,k,count);
        }
        if (a[m] < k)
        {
            (*count)++;
            return binarysearch(a,m+1,r,k,count);
        }
        if (a[m] == k)
        {
            (*count)++;
            return m;
        }
    }
    if (r <= l)
    {
        (*count)++;
        if (k>a[l]) return l+1;
        else return l;
    }
}

关于c - Count指针的值不变,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46134577/

10-11 20:15