prova con realloc()
Ecco un esempio che ho testato:
codice:
#include <malloc.h>
#include <iostream.h>
int main() {
int* s = (int*)malloc(10*sizeof(int));
int max = 10;
int now = 0;
for(register int i = 0; i < 20; i++) {
s[i] = i;
cout << s[i] << endl;
now++;
if(now == max-1) {
max *= 2;
s = (int*)realloc((void*)s, sizeof(int)*max);
}
}
cout << "Aggiunti altri 30\n";
max += 30;
s = (int*)realloc((void*)s, sizeof(int)*max);
for(register int j = 0; j < 30; j++) {
s[j] = j;
cout << s[j] << endl;
}
return 0;
}
forse è + giusto così:
codice:
#include <malloc.h>
#include <iostream.h>
int main() {
int* s = (int*)malloc(10*sizeof(int));
int max = 10;
int now = 0;
for(register int i = 0; i < 20; i++) {
s[i] = i;
cout << s[i] << endl;
now++;
if(now == max-1) {
max *= 2;
s = (int*)realloc((void*)s, sizeof(int)*max);
}
}
cout << "Aggiunti altri 30\n";
max += 30;
s = (int*)realloc((void*)s, sizeof(int)*max);
for(register int j = 19; j < 19+30; j++) {
s[j] = j;
cout << s[j] << endl;
}
return 0;
}