C realloc usage

六月ゝ 毕业季﹏ 提交于 2019-12-12 00:58:58

问题


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]);
    }
}

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/16958376/c-realloc-usage

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!