2017-10-21 43 views
0

我遇到一些奇怪的C行为。我有一个数组(我标记为SHOULD_NOT_CHANGE)在一个看似无关的函数调用后发生了变化。我的数组不是全局的,函数调用不包括特定的数组。如果任何人能够弄清楚发生了什么,我将不胜感激。下面是主要的:阵列由无关函数改变

int main(){ 




    int generate4[16] = {0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; 
    int propagate4[16] = {0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0}; 

    int SHOULD_NOT_CHANGE[4] = {0, 1, 0, 0}; 

    int carry_in16[4] = {1,2,1,1}; 
    int carry_in4[16] = {0}; 



    printf("\nShould be 1: %d", SHOULD_NOT_CHANGE[0]); 
    printf("\nShould be 0: %d", SHOULD_NOT_CHANGE[1]); 

    printf("\nSHOULD NOT CHANGE : "); 
    print_binary_array(SHOULD_NOT_CHANGE, 4); 



    // Here is where the problem is 
    carry(propagate4, generate4, carry_in4, carry_in16, 64, 4); 



    printf("\n\nShould be 0: %d", SHOULD_NOT_CHANGE[0]); 
    printf("\nShould be 1: %d", SHOULD_NOT_CHANGE[1]); 

    printf("\nSHOULD NOT CHANGE : "); 
    print_binary_array(SHOULD_NOT_CHANGE, 4); 

    return 0; 
} 

这里是罪魁祸首功能:

void carry(int* p, int* g, int* carry_in, int* group_carry, int size, int block) 
{ 

for (int j = 0; j < block; j++){ 
    carry_in[j] = g[j] + p[j] * group_carry[j]; 

    for (int i = 1; i < block*4; i++){ 
     carry_in[4*j+i] = g[4*j+i] + p[4*j+i] * group_carry[j]; 
    } 
} 
} 

这里是我的输出:

Should be 0: 0 
Should be 1: 1 
SHOULD NOT CHANGE : 0010 

Should be 0: -13136 
Should be 1: 0 
SHOULD NOT CHANGE : 1-21471898220-13136 
+0

'carry_in [4 * j + i]' - 这将在最大值处评估为carry_in [4 * 3 + 15],这意味着您将读取数组的末尾,导致未定义的行为一个段错误不能保证)。 –

+0

@KarlReid请发表您的评论作为回答,以便OP可以接受它。 –

回答

1

您索引过去carry_in界限的功能carryblock是4,所以4*block是16.所以j从0运行到3,而i运行从1到15.所以4*j+i可以大到12 + 15 = 27,这就是的方式大于最大安全值15.

+0

谢谢!我修复了for循环,它解决了我的问题。 – charge3