49

我有以下代码

FRAME frameArray[5][10]; // Create the array of frames
int trackBufferFull[5] = {0, 0, 0, 0, 0};// Keeps track of how full the buffer for each node is
int trackFront[5] = {0, 0, 0, 0, 0}; // Array to keep track of which is the front of the array
int trackTail[5] = {0, 0, 0, 0, 0};


// Function to add to the array (CHANGE int frame)
void addFrame (int nodeNumber, FRAME frame)
{
    //Calc tail
    int tail = trackTail[nodeNumber-1];

    // Calc frames in buffer
    int framesinBuffer = trackBufferFull[nodeNumber-1];

    if (framesinBuffer == 10)
    {
        printf("Buffer is full\n");
    }
    else
    {

        // Add frame to frameArray
        frameArray[nodeNumber-1][tail] = frame; 
        printf("\nAdded a frame in node: %i to the buffer\n", nodeNumber);

        // Increment the count
        trackBufferFull[nodeNumber-1]++;
        trackTail[nodeNumber-1] = ++trackTail[nodeNumber-1] % 10;


    }  
}

我用于 frameArray 的数组是长度为 10 的环绕/循环数组,因此我有代码

trackTail[nodeNumber-1] = ++trackTail[nodeNumber-1] % 10;

一切都在独立文件中完美运行,但是在更大的文件中运行时,出现以下编译错误:

$ cnet GARETH -m 30
compiling gareth.c
gareth.c: In function ‘addFrame’:
gareth.c:77:27: error: operation on ‘trackTail[nodeNumber + -0x00000000000000001]’ may be undefined [-Werror=sequence-point]
gareth.c: In function ‘removeFirstFrame’:
gareth.c:98:28: error: operation on ‘trackFront[nodeNumber + -0x00000000000000001]’ may be undefined [-Werror=sequence-point]
gareth.c:105:1: error: control reaches end of non-void function [-Werror=return-type]
cc1: all warnings being treated as errors

77号线是线

trackTail[nodeNumber-1] = ++trackTail[nodeNumber-1] % 10;

帮助。

为了并排查看带有行号的代码和错误,我将图片上传到:http: //i.imgur.com/wyO5a.png

4

3 回答 3

72

77号线是线

trackTail[nodeNumber-1] = ++trackTail[nodeNumber-1] % 10;

您在序列点trackTail[nodeNumber-1]之间更改了两次:一次通过,一次通过分配。++

这是未定义的行为

补救措施是改写语句,例如:

trackTail[nodeNumber-1] = (trackTail[nodeNumber-1] + 1) % 10;

或者像这样:

trackTail[nodeNumber-1]++;
trackTail[nodeNumber-1] %= 10;
于 2012-05-16T16:55:01.357 回答
9

您正在trackTail[nodeNumber - 1]序列点之间进行修改。就像你在分配

i = ++i;

这也是未定义的行为。

将您的代码更改为以下内容:

trackTail[nodeNumber - 1] = (trackTail[nodeNumber - 1] + 1) % 10;
于 2012-05-16T16:54:46.660 回答
6
trackTail[nodeNumber-1] = ++trackTail[nodeNumber-1] % 10;

是的,正如错误消息所说,这是未定义的行为。在没有序列点的情况下,您不能两次修改相同的值。在这种情况下,这意味着您不能同时trackTail[nodeNumber-1]使用递增++和重新分配它=

如果您只使用+ 1而不是++,它将正常工作。

于 2012-05-16T16:55:47.433 回答