#include<iostream>
#include<algorithm>
#include<malloc.h>
#include<stdlib.h>
using namespace std;
typedef struct _intExpandArray{
int size;
int max;
int *base;
} intExpandArray;
void addExpandArrayElement(intExpandArray *arr, int element){
int *p;
if(arr->base == NULL){
arr->base = (int* )malloc(2*sizeof(int));
arr->size = 0;
arr->max = 2;
cout<<"base = " << arr->base <<endl;
}else if(arr->size >= arr->max){
p = (int *)realloc(arr->base, arr->max*2*sizeof(int));
if(p != NULL){
cout<<"reallocate successful base = " << arr->base << endl;
arr->max *= 2;
}else{
cout<<"reallocate failed base = "<< arr->base <<endl;
}
}
*(arr->base + arr->size) = element;
arr->size++;
}
/* display array */
void dispIntExpandArray(intExpandArray arr){
int i;
int n = arr.size;
int *p = arr.base;
cout<< "size = " << n << " max size = " << arr.max << endl;
for(i = 0; i < n; i++){
cout<<p[i]<<" ";
}
cout<<endl;
}
int main(){
intExpandArray arr;
arr.base = NULL;
int i = 0;
for(i = 0; i < 10; i++){
addExpandArrayElement(&arr, i);
//dispIntExpandArray(arr);
}
return 0;
}
为什么我不能重新分配内存?(我的window操作系统上还有很多内存)当我运行这段代码时,malloc函数工作得很好,但realloc函数只工作了一次,第二次就失败了,所以我得到一个"reallocate base = ...“消息和6“重新分配失败基础= ...”消息
发布于 2015-06-07 21:13:51
在调用realloc
之后,您忘记了重置arr->base
的值。
使用:
p = (int *)realloc(arr->base, arr->max*2*sizeof(int));
if(p != NULL){
arr->max *= 2;
arr->base = p; // Missing line
cout<<"reallocate successful base = " << arr->base << endl;
}else{
cout<<"reallocate failed base = "<< arr->base <<endl;
}
https://stackoverflow.com/questions/30698463
复制相似问题