I am having an issue where editing array A is affecting array B in C when using pointers. My code is the following:
#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() just prints out the contents of heap along with the fractions sign, numerator, and denominator. However, the output when I run this code is the following:
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 See the 1s in the numerator place in numerous fractions in the fractions array even though I never told it to put 1s there? This doesnt happen if I edit out the call to init_heap(). If I edit out the call to init_heap the output is:
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 Which is correct. My question is why is init_heap affecting the fractions array even though in init_heap I am only editing and accessing the freeBlocks array?
heap(for example) is an array with a single entry, and that entry is an array ofARRAYSIZEfractions. This means you can't do e.g.heap[x]ifxis larger than zero, as that will be out of bounds!