0

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]);
    }
}
eddie
  • 1,252
  • 3
  • 15
  • 20
William McCarty
  • 769
  • 3
  • 12
  • 26

2 Answers2

5

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.

Xaqq
  • 4,308
  • 2
  • 25
  • 38
  • Ok, I was going off this post "http://stackoverflow.com/questions/37538/how-do-i-determine-the-size-of-my-array-in-c" Whats the difference between these two??? my array is technically the same is it not?? – William McCarty Jun 06 '13 at 09:40
  • 1
    Just a FYI: `void*` and `int*` do not necessarily have the same size (and alignment requirements and padding and ...). – pmg Jun 06 '13 at 09:53
  • @pmg oO didn't know about that. Alignment requirements and padding can make sense, but the size. Do you have any links explaining why and when? I thought all pointer had the same size. – Xaqq Jun 06 '13 at 09:54
  • @Xaqq: They don't have to. They just have to be convertible to and from a `void *`. – Hasturkun Jun 06 '13 at 10:19
  • @Xaqq: see [6.2.5/27 in the C99 Standard](http://port70.net/~nsz/c/c99/n1256.html#6.2.5p27). *"Pointers to other types need not have the same representation or alignment requirements."* – pmg Jun 06 '13 at 10:29
  • Answer edited, feel free to re-edit if it's not accurate enough :) – Xaqq Jun 06 '13 at 12:25
1

sizeof(fibs) is the size of the pointer fibs which is constant, therefore your printing function will always print the same number of elements

Joe
  • 6,497
  • 4
  • 29
  • 55