从C中的数组中删除负数

时间:2013-12-21 00:47:32

标签: c arrays

我正在尝试使用以下代码从数组中删除负数。不幸的是,没有得到结果。它只是反复打印第一个元素。有人可以告诉我哪里出错了吗?

#include <stdio.h>
void removenegative(int a[],int *p, int *q);
int main()
{
    int a[] = {2, 3, -5, -7, 6, 9};
    int i;
    int *p, *q;
    p = a;
    q = a+6-1;
    removenegative(a, p,q);
    for(i=0;i<6;i++)
        {
            printf("%2d", *p);
        }
    printf("\n");
}
void removenegative(int a[],int *p, int *q)
{
    int *x;
    x= &a[0];
    while (p<=q)
        {
            if (*p>=0)
                {
                    *x = *p;
                    x++;
                }
            p++;
        }
    for( ; x<=q; x++)
        {
            *x = -1;
        }
}

5 个答案:

答案 0 :(得分:4)

for(i=0;i<6;i++)
    {
        printf("%2d", *p);
    }

您没有更改p

答案 1 :(得分:4)

您只打印一个值:

printf("%2d", *p);

for循环之前执行此操作:

p = a;

并在循环内添加p++;

答案 2 :(得分:4)

  

它只是反复打印第一个元素

当然是这样......

    for(i=0;i<6;i++)
    {
        printf("%2d", *p);
    }

您始终打印* p,即[0]

答案 3 :(得分:2)

变化:

printf("%2d", *p);

为:

printf("%2d", a[i]);

您正在循环i,但没有使用它。

答案 4 :(得分:1)

您的代码是正确的:

void removenegative(int a[],int *p, int *q)
{
    int *x;
    x= &a[0]; // let x point to the first thing in a

    while (p<=q) // continue while p points to an address before q
        {
            if (*p>=0)  // if the thing pointed to by p is greater than zero...
                {
                    *x = *p;  // copy from p to x, increment x
                    x++;
                }
            p++;  // increment p
        }
    for( ; x<=q; x++) // while x is less than q...
        {
            *x = -1;  // fill in -1
        }
}

因此x是一个递增的写指针,而p扫描数组,q充当数组结束标记。

因为我在打字时打了个骂,你的输出程序是不正确的。

相关问题