Ç使用的realloc [英] C realloc usage

查看:170
本文介绍了Ç使用的realloc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着去动态地增加一个int数组的内存,但是林有得到它的工作的问题。它不扩大,增加更多的元素数组,林不知道什么即时通讯做错了,请帮助。

 为int *避免信口开河= NULL;无效genFibs(){
    INT I = 1,curSize = 0,curNum = 0;
    INT标志= 1;
    而(标志){
        如果(curSize = 0&放大器;!&放大器;!curSize = 1){
            curNum = FIB中[curSize-2] +的FIB [curSize-1];
        }否则如果(curSize-1 == 1){
            curNum = FIB中[curSize-1] +的FIB [curSize-1];
        }其他{
            curNum = 1;
        }
        如果(curNum&下; = 10){
            curSize ++;
            小谎=(INT *)的realloc(避免信口开河,curSize *的sizeof(INT));
            的FIB [curSize-1] = curSize;
        }其他{
            标志= 0;
        }
    }
  }
}无效printFibs(){
    INT大小= sizeof的(小谎)/的sizeof(int);在
    INT I = 0;
    对于(i = 0; I<大小;我++){
        的printf(%d为:%d个\\ N,我,小谎[I]);
    }
}


解决方案

那么,你的打印code是错误的。 的sizeof(小谎)总是被评价为的sizeof(INT *),因为它只是一个指针。

您必须找到一种方法来尺寸传递给你的打印功能。它可以是例如阵列的第一个值。但是,这是实现细节,就看你了。

编辑:更改的sizeof(无效*)的sizeof(INT *),因为指针的大小可能会有所不同,如由PMG指出。

Im trying to dynamically increase memory of an int array, However Im having issues getting it to work. It isn't expanding and adding more elements to the array, Im not sure what im 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]);
    }
}

解决方案

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.

这篇关于Ç使用的realloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆