Ridistribuzione della memoria
È possibile molte volte mentresiete programmando iete programmando che desiderate ridistribuire la memoria. Ciò è fatta con la funzione del realloc. La funzione del realloc prende due parametri, l'indirizzo basso della memoria che desiderate ridimensionare e la quantità di spazio desiderate riservare e ritorni un indicatore all'indirizzo basso.
Supporre che abbiamo riservato lo spazio ad un indicatore denominato msg e desideriamo ridistribuire lo spazio alla quantità di spazio già prende, più la lunghezza di un'altra stringa allora potremmo usare quanto segue.
msg = (char *)realloc(msg, (strlen(msg) + strlen(buffer) + 1)*sizeof(char));
Il seguente programma illustra l'uso di malloc, realloc e libera. L'utente entra in una serie di stringhe che si uniscono insieme. Il programma arresta le stringhe della lettura quando una stringa vuota è inserita.
#include <string.h>
#include <malloc.h>
int main()
{
char buffer[80], *msg;
int firstTime=0;
do
{
printf("\nEnter a sentence: ");
gets(buffer);
if (!firstTime)
{
msg = (char *)malloc((strlen(buffer) + 1) *
sizeof(char));
strcpy(msg, buffer);
firstTime = 1;
}
else
{
msg = (char *)realloc(msg, (strlen(msg) +
strlen(buffer) + 1) * sizeof(char));
strcat(msg, buffer);
}
puts(msg);
} while(strcmp(buffer, ""));
free(msg);
return 0;
}
L'uscita del programma sarà come segue:
Enter a sentence: Once upon a time
Once upon a time
Enter a sentence: there was a king
Once upon a timethere was a king
Enter a sentence: the king was
Once upon a timethere was a kingthe king was
Enter a sentence:
Once upon a timethere was a kingthe king was |
|