Reputation: 839
I'm trying to dynamically increase memory of an int
array, However I'm having issues getting it to work. It isn't expanding and adding more elements to the array, I'm not sure what I'm doing wrong.
Please help!
int* fibs = NULL;
void genFibs(){
int i = 1,curSize = 0,curNum = 0;
int flag = 1;
while(flag){
if(curSize != 0 &&curSize != 1){
curNum = fibs[curSize-2]+fibs[curSize-1];
}else if(curSize-1 == 1){
curNum = fibs[curSize-1]+fibs[curSize-1];
}else{
curNum = 1;
}
if(curNum<=10){
curSize++;
fibs = (int*)realloc(fibs,curSize*sizeof(int));
fibs[curSize-1] = curSize;
}else{
flag = 0;
}
}
}
}
void printFibs(){
int size = sizeof(fibs)/sizeof(int);
int i = 0;
for(i = 0;i<size;i++){
printf("%d is: %d\n",i,fibs[i]);
}
}
Upvotes: 0
Views: 207
Reputation: 4386
Well, your print code is wrong. sizeof(fibs)
will always be evaluated as sizeof(int *)
because its just a pointer.
You have to find a way to pass the size
to your print
function. It could be, for example the first value of your array. But this is implementation detail and it's up to you.
EDIT: Changed sizeof(void *)
to sizeof(int *)
because pointer size may vary, as pointed out by pmg.
Upvotes: 5
Reputation: 6777
sizeof(fibs)
is the size of the pointer fibs
which is constant, therefore your printing function will always print the same number of elements
Upvotes: 1