需要帮助找到为什么for循环的计数器变量被循环内的函数改变的原因

swi*_*ano 3 c for-loop

我的循环中的一个函数以某种方式改变了我迭代的值,我不确定如何.如果描述得很糟,我很抱歉.

在这个for循环中

int k;

for( k = 0; k < 512; k++)
{
    // Discardheader(d);      // doesnt actually do anything, since it's a header.f
    int databit = Getexpecteddata(d+4*k+1);
    printf("%d ",k);
    int transmitted = Datasample(&datastate, &datalength, d+4*k+2,dataerr,dataloc, databit);
    printf("%d ",k);
    Clocksample(&clockstate, &clocklength, d+4*k+3,clockerr, transmitted); 
    printf("%d \n",k);

}
Run Code Online (Sandbox Code Playgroud)

我得到这个输出

16 16 16
17 17 17
18 18 18
19 19 19
20 20 20
21 1 1
2 2 2
3 3 3
4 4 4
Run Code Online (Sandbox Code Playgroud)

所以Datasample一旦达到21就会改变k的值.d是char*d类型,表示我读取文件的缓冲区.更改输入文件不会改变21,切换发生.这是数据样本的代码:

int Datasample (int* state, int* length, char *d, int *type, int location, int data)
{
    int match = 1;                                  // if data sample and delayed tx match,
    if ( ((d[0] >> location) & 1) != data)
    {
        match = 0;
        if(data)
    {
        type[2]++;  
    }
    else
    {
        type[1]++;
    }   

} 

int ia;
for( ia = 7; ia>=0; ia--)                           
{
    if ( ((d[0] >> ia) & 1) == *state)          // finds an edge
    {
        *length++;
    }
    else
    {
        int distance, deviation,devflag=1;      // distance the edge is from the sample point. should be about 4
        if ( location > 3)                      // deviation is how far the distance then is from 4
        {distance = location - ia;}
        else
        {distance = ia - location;}

        deviation = abs(4-distance);

        if( (deviation >= devmax) && match && devflag)
        {
            devflag =0;    
            if(data)
            {
                type[2]++;  
            }
            else
            {   
                type[1]++;
            }   

        }
        *state = ((d[0] >> ia) & 1);
        *length = 1;
    }

}

return ((d[0] >> location) & 1);
Run Code Online (Sandbox Code Playgroud)

}

是什么导致k一旦击中21就回滚到1?

提前致谢.我不知道我在做什么.

cni*_*tar 5

看看你的输出,这个Datasample函数很可能会对内存做一些有趣的事情.

我看到的第一个问题是你传递一个整数作为函数的第三个参数,并且指向一个指针.这让我相信你在没有警告的情况下进行编译.这是真正的问题.

编辑

根据最近的评论,事实证明d它实际上是一个指针.但是,我坚持认为该功能中的某些东西会写下来k.

由于正在使用Linux上的gcc,您可以尝试valgrind快速查明问题.它应该警告你非法访问内存.