赋值使得指针没有强制转换

时间:2014-05-07 04:54:14

标签: c pointers casting warnings variable-assignment

我正在编辑一个快速排序代码,以便low,high和middle的值指向数组元素而不是整数。

这是我的代码:

#include <stdio.h>

#define N 10

void quicksort(int a[], int *low, int *high);
int split(int a[], int *low, int *high);

int main(void)
{
    int a[N], i;
    printf("Enter %d numbers to be sorted: ", N);
    for (i=0; i<N; i++)
        scanf("%d", &a[i]);
    quicksort(a, &a[0], &a[N-1]);

    printf("In sorted order: ");
    for (i=0; i<N; i++)
        printf("%d ", a[i]);
    printf("\n");

    return 0;
}

void quicksort(int a[], int *low, int *high)
{
    int *middle;

    if (low >= high) return;
    middle = split(a, low, high);
    quicksort(a, low, middle - 1);
    quicksort(a, middle + 1, high);
}

int split(int a[], int *low, int *high)
{
    int part_element = *low;

    for (;;) {
        while (low < high && part_element <= *high)
            high--;
        if (low >= high) break;
        *low++ = *high;

        while (low < high && *low <= part_element)
            low++;
        if (low >= high) break;
        *high-- = *low;
    }

    *high = part_element;
    return *high;
}

我收到错误消息:

qs.c:32:12: warning: assignment makes pointer from integer without a cast [enabled by default]
 middle = split(a, low, high);
        ^

有人可以帮我吗?仍然是编程的初学者。所有类型的帮助都表示赞赏。

2 个答案:

答案 0 :(得分:1)

问题出在本声明中。

middle = split(a, low, high);

因为middle是指针变量,而split是一个返回整数值而不是指向整数的指针的函数。

您正在为指针变量middle分配整数值。 你不被允许这样做。 :)

可能会对你有帮助。

答案 1 :(得分:0)

更改'split()'以返回'int *'而不是'int'。

从'

更改'split()'函数的最后一行
return *high;

return high;

也许这会更好:

#include <stdio.h>

#define N 10

void quicksort(int a[], int *low, int *high);
int *split(int a[], int *low, int *high);

int main(void)
{
    int a[N], i;
    printf("Enter %d numbers to be sorted: ", N);
    for (i=0; i<N; i++)
        scanf("%d", &a[i]);
    quicksort(a, &a[0], &a[N-1]);

    printf("In sorted order: ");
    for (i=0; i<N; i++)
        printf("%d ", a[i]);
    printf("\n");

    return 0;
}

void quicksort(int a[], int *low, int *high)
{
    int *middle;

    if (low >= high) return;
    middle = split(a, low, high);
    quicksort(a, low, middle - 1);
    quicksort(a, middle + 1, high);
}

int *split(int a[], int *low, int *high)
{
    int part_element = *low;

    for (;;) {
        while (low < high && part_element <= *high)
            high--;
        if (low >= high) break;
        *low++ = *high;

        while (low < high && *low <= part_element)
            low++;
        if (low >= high) break;
        *high-- = *low;
    }

    *high = part_element;
    return high;
}