如何在运行时增加数组大小以避免最后的垃圾值

时间:2016-10-20 04:39:22

标签: c arrays dynamic-memory-allocation

这里我正在使用一个代码来计算" 1"一次出现在一个数组中,我的数组是

int arr[12] = {0,1,1,0,0,1,1,1,1,0,0,1};

Number of "1" present at a time are (2,4,1)

我想将结果存储在一个数组calle store 中。由于序列可能会有所不同,一开始我不知道我必须声明存储它们的数组大小。最坏的情况是可能会有如下数组:

int arr[12]={0,1,0,1,0,1,0,1,0,1,0,1};

所以我动态分配了一个实际数组大小一半的数组来存储最坏的情况。但如果不是最坏的情况我在存储数组的末尾得到垃圾值。我想知道如何动态增加数组大小在运行时,所以我不需要处理任何垃圾值

#include<stdio.h>
#include<stdlib.h>

int main(){

   int arr[12] = {0,1,1,0,0,1,1,1,1,0,0,1};
   int size = sizeof(arr)/sizeof(arr[0]);

   int *store =(int *)malloc((size/2)*sizeof(int));

   int i=0,j=0,count=0;
   while(arr[i]<size){
        while(arr[i]==0 && arr[i]<size){
            i++;
        }
        if(i==size){
           break;
        }
        while(arr[i]==1){
            i++;
            count++;
        }
        store[j]=count;
        j++;
        count=0;
   }
   for(i=0;i<size/2;i++){

       printf("%d ",store[i]);
   }

}

2 个答案:

答案 0 :(得分:1)

使用n <- 100000 prob1 <- 0.99 prob2 <- 1-prob1 dist1 <- rnorm(prob1*n, 0, 1) dist2 <- rnorm(prob2*n, 0, 10) actual_sample <- c(dist1, dist2)

realloc

答案 1 :(得分:0)

您可以使用calloc

store = calloc(store,sizeof(int));