arrays - C Pointers pointing to wrong objects -
in code, have array of 10 fraction objects, , testing purposes wanted edit first fraction in array. .h file follows:
/*frac_heap.h*/ /*typedefs*/ typedef struct { signed char sign; unsigned int denominator; unsigned int numerator; }fraction; typedef struct { unsigned int isfree; }block; void dump_heap(); void init_heap(); fraction* new_frac(); in .c file following:
// file frac_heap.c #include <stdio.h> #include <stdlib.h> #include "frac_heap.h" #define arraysize 10 fraction* heap[arraysize] = {}; block* freeblocks[arraysize] = {}; 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(); fraction *p1; p1 = new_frac(); p1->sign = -1; p1->numerator = 2; p1->denominator = 3; dump_heap(); return 0; } the output of dump_heap() should list 10 fractions (their sign, numerator, , denominator), fraction 1 being 1 changed. however, output following:
-1 2 3 3 0 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 how fractions 2 , 3 being edited when have pointer fraction 1 p1? using pointers wrong?
either need malloc() structures or define fixed size arrays of fraction (if size fixed.
alternative #1:
fraction heap[arraysize][10] = {}; alternative #2:
fraction* heap[arraysize] = {}; void init_heap(){ int x; for(x = 0; x < arraysize; x ++){ block *currblock = &freeblocks[x]; currblock->isfree = 1; /*malloc fractions*/ heap[x] = (fraction*)malloc( sizeof(fraction)); heap[x]->numerator=0; heap[x]->denominator=0; heap[x]->sign=0; } } void dump_heap(){ ... fraction* tempfrac = heap[x]; /*you cannot de-reference heap*/ ... } fraction* new_frac(){ ... fraction* testfraction = heap[0]; ... }
Comments
Post a Comment