0

我遇到了一个问题,即在使用指针时编辑数组 A 会影响 C 中的数组 B。我的代码如下:

#include <stdio.h>
#include <stdlib.h>
#include "frac_heap.h"

#define ARRAYSIZE 10

fraction heap[][ARRAYSIZE] = {0};
block freeBlocks[][ARRAYSIZE] = {0};
int startingBlock = 0;

void init_Heap(){
    int x;
    for(x = 0; x < ARRAYSIZE; x ++){    

        block *currBlock = freeBlocks[x];
        currBlock->isFree = 1;  
    }
}



void dump_heap(){
    int x;
    for(x = 0; x < ARRAYSIZE; x ++){
        fraction* tempFrac = heap[x];
        printf("%d\t%d\t%d\n",tempFrac->sign, tempFrac->numerator, tempFrac->denominator);
    }   
}


fraction* new_frac(){
    fraction* testFraction = heap[0];
    return testFraction;
}




int main(){ 
    init_Heap();
    dump_heap();
    fraction *p1;
    p1 = new_frac();
    p1->sign = -1;
    p1->numerator  = 2; 
    p1->denominator = 3;
    dump_heap();    
   }

dump_heap() 只打印出堆的内容以及分数符号、分子和分母。但是,当我运行此代码时的输出如下:

0   0   0
0   1   0
0   1   0
0   1   0
0   1   0
0   0   0
0   0   0
0   0   0
0   0   0
0   0   0

-1  2   3
0   1   0
0   1   0
0   1   0
0   1   0
0   0   0
0   0   0
0   0   0
0   0   0
0   0   0

看到分子中的 1 在分数数组中的许多分数中出现,即使我从未告诉过它把 1 放在那里?如果我编辑对 init_heap() 的调用,则不会发生这种情况。如果我编辑对 init_heap 的调用,则输出为:

0   0   0
0   0   0
0   0   0
0   0   0
0   0   0
0   0   0
0   0   0
0   0   0
0   0   0
0   0   0

-1  2   3
0   0   0
0   0   0
0   0   0
0   0   0
0   0   0
0   0   0
0   0   0
0   0   0
0   0   0

哪个是对的。我的问题是为什么 init_heap 会影响分数数组,即使在 init_heap 我只是编辑和访问 freeBlocks 数组?

4

3 回答 3

1

Don't declare your arrays as heap[][ARRAYSIZE], it doesn't make any sense, especially not in the way you are trying to use them. Instead, declared them as heap[ARRAYSIZE].

于 2013-04-10T06:34:52.173 回答
1

From the way you're using them, it seems that heap and freeBlocks are meant to be 1D arrays, not 2D.

If that's the case, the following:

fraction heap[][ARRAYSIZE] = {0};
block freeBlocks[][ARRAYSIZE] = {0};

should become

fraction heap[ARRAYSIZE] = {0};
block freeBlocks[ARRAYSIZE] = {0};
于 2013-04-10T06:35:05.730 回答
1

I think your problem lies in these two definitions:

fraction heap[][ARRAYSIZE] = {0};
block freeBlocks[][ARRAYSIZE] = {0};

Each defines an array with size 1 for the leading dimension, because you only provide 1 initializer.

int x;
for (x = 0; x < ARRAYSIZE; x ++){    

    block *currBlock = freeBlocks[x];
    currBlock->isFree = 1;  
}

This code is indexing through the array of arrays one unit of 10 blocks at a time (and is trampling way out of bounds). freeblocks[1] is beyond the end of the space allocated for freeblocks; freeblocks[9] is even further out of control.

于 2013-04-10T06:35:31.797 回答