[英]How to increase array size during runtime to avoid garbage value at the end
Here i am working with a code which will count the number of "1" present in an array at a time.say, my array is 在这里,我正在使用一个代码,该代码一次计算一个数组中存在的“ 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)
I want to store the result in an array calle store .As the sequence can vary,At the very beginning i don't know what size of array i have to declare to store them.Worst case will be there might be a array like the following: 我想将结果存储在数组calle 存储区中 。由于顺序可能会有所不同,一开始我不知道必须声明要存储的数组大小。最坏的情况可能是像这样的数组以下:
int arr[12]={0,1,0,1,0,1,0,1,0,1,0,1};
so i dynamically allocated an array half the size of actual array to store the worst case.But If not the worst case i get garbage value at the end of store array.I would like to know how i can dynamically increase array size at runtime so that i don't need to deal with any garbage value 所以我动态分配了一个数组的大小来存储最坏情况的数组,但如果不是最坏情况,我会在存储数组末尾得到垃圾值。我想知道如何在运行时动态增加数组大小,以便我不需要处理任何垃圾值
#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]);
}
}
Use realloc
使用重新
realloc
//size2 has the size of the new array to be stored
store = realloc(store, size2 * sizeof int);
if (store == NULL)
{
// Reallocation failed -- Take appropriate action
printf ("Reallocation failed");
exit(1);
}
您可以使用calloc
store = calloc(store,sizeof(int));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.