【问题标题】:Realloc int array's new spaces in memory to 0Realloc int 数组在内存中的新空间为 0
【发布时间】:2017-03-29 16:10:10
【问题描述】:

我有一个 int 数组,当它看到比它已经拥有的更高的 int 值时需要增长,有没有办法调用 realloc() 并设置正在创建的内存中的所有新空间?还是我需要遍历内存中的所有新空间并将它们一一设置为0?为了清楚起见,下面的代码。

int main(){
    int i;
    int currentSize = 10;
    int *checkList = malloc(sizeof(int) * currentSize);
    while((i = readInt(fp))){
        if(i > currentSize){
             currentSize = i + 1;
             checklist = realloc(checkList, sizeof(int) * (i + 1));
             //Need to loop through checklist and declare empty mem to 0?
        } 
        if(!checkList[i]) checkList[i]++;
    }

    //should have an array where seen values index in checklist == 1
}

【问题讨论】:

  • mallocrealloc 都不会初始化它分配的内存。如果您希望以任何方式初始化它,您需要调用 calloc 或使用 memset 自己进行。
  • 所以我需要分配一个新数组,将所有这些设置为 0,然后将值逐项复制到新数组中
  • 不,只是初始化新元素。
  • if(i > currentSize) 应该是 if(i >= currentSize),因为(例如)如果 i 是 10,则超出了分配的初始范围。
  • 建议以int currentSize = 0; int *checkList = NULL;开头

标签: c arrays pointers realloc


【解决方案1】:

这是您可以如何执行reallocation - 它将其扩展为newSize,然后使用memset 将新元素设置为0。

if(i >= currentSize) {
     int newSize = i + 1;
     checkList = realloc(checkList, sizeof(int) * newSize);
     memset(checkList+currentSize,0,sizeof(int) * (newSize - currentSize));
     currentSize = newSize;
} 

您可能希望在初始分配时使用 memsetcalloc 以确保这些值也是 0 BTW。

【讨论】:

    【解决方案2】:

    您可以使用memset 将特定内存范围内的所有值设置为预期值,而不是循环。

    你的代码可以像下面这样修改以使用 memset

    int main(){
        int i;
        int currentSize = 10;
        int *checkList = malloc(sizeof(int) * currentSize);
        while((i = readInt(fp))){
            if(i >= currentSize){
                 checklist = realloc(checkList, sizeof(int) * (i + 1));
                 //Need to loop through checklist and declare empty mem to 0?
                 memset(checklist+currentSize, 0, (sizeof(int) * ((i+1) - currentSize)));
                 currentSize = i + 1;
            } 
            if(!checkList[i]) checkList[i]++;
        }
    
        //should have an array where seen values index in checklist == 1
    }
    

    【讨论】:

    • 所以我可以在原始数组之外的范围上使用realloc 然后memset
    • realloc 会给你连续的内存。您可以使用 memset 对已分配的那部分内存进行 memset。
    • @chux - 完成! :)
    猜你喜欢
    • 1970-01-01
    • 2022-11-22
    • 2017-10-15
    • 2019-02-03
    • 1970-01-01
    • 2011-05-01
    • 2011-04-10
    • 2012-11-01
    • 1970-01-01
    相关资源
    最近更新 更多