-1

假设,数组总是连续的,我想知道现在我正在做 memcpy 的 QPop 函数是否有什么问题?

-- C snip ---------
    int Q[5];
    int QPush();
    static int pushIdx;
    int QPush (int *q, int val)
    {
        int ret=0;

        if ( isQFull(q) )
            return -1;

        q[pushIdx++] = val;
        return ret;
    }

    int QPop ( int *q)
    {
        int i, ret=0;
        unsigned long size = pushIdx -1 ;

        if ( isQEmpty(q) )
            return -1;

        ret = q[0];

        if ( size > 0 )
            memcpy ( q, q+1, (size*sizeof(int)) );

        q[pushIdx-1] = 0;
        pushIdx--;
        return ret;
    }

    int main()
    {
    QPush(&Q , 11);
    QPush(&Q , 12);
    QPush(&Q , 13);

    printf ( "pop = %d ", QPop(&Q));
    printf ( "pop = %d ", QPop(&Q));
    }

谢谢。-Nathan 它在我的所有条件下测试都很好[平台最新的 Linux gcc],所以我正在寻找一个它可能会破坏的案例。

4

1 回答 1

3

According to the manual of memcpy(), the memory areas must not overlap. But, your memory areas will. You should use memmove() for overlapping areas.

于 2013-03-18T21:27:44.293 回答