Concetti Chiave
- Il programma chiede all'utente di inserire il numero di righe e colonne per una matrice dinamica.
- Utilizza la funzione malloc per allocare memoria per una matrice bidimensionale in C.
- Permette all'utente di inserire gli elementi della matrice tramite input da tastiera.
- Stampa la matrice formattata in output con spazi di cinque caratteri per ogni elemento.
- Gestisce la deallocazione della memoria utilizzando la funzione free per evitare perdite di memoria.
int main ()
[/p]
[p]
{
[/p]
[p]
int **matrice;
[/p]
[p]
[b]int righe, colonne[/b], r, c;
[/p]
[p]
[b]printf[/b](“Digita il numero di righe della matrice: “);
[/p]
[p]
[b]scanf[/b](“%d”,&righe);
[/p]
[p]
printf(“Digita il numero di colonne della matrice: “);
[/p]
[p]
scanf(“%d”,&colonne);
[/p]
[p]
//allocazione della matrice
[/p]
[p]
matrice = (int **) malloc (righe*sizeof(int *));
[/p]
[p]
[/p]
[h2]inserimento dati[/h2]
[p]
for(r=0; r<righe; r++)
[/p]
[p]
matrice[r] = (int *) malloc(colonne*sizeof(int));
[/p]
[p]
//inserimento dati
[/p]
[p]
for(r=0; r<righe; r++)
[/p]
[p]
for(c=0; c<colonne; c++)
[/p]
[p]
{
[/p]
[p]
printf(“Inserisci elemento di riga %d e colonna %d: “, r,c);
[/p]
[p]
scanf(“%d”,&matrice[r][c]);
[/p]
[p]
}
[/p]
[p]
//stampa della matrice
[/p]
[p]
for(r=0; r<righe; r++)
[/p]
[p]
{
[/p]
[p]
for(c=0; c<colonne; c++)
[/p]
[p]
printf(“%5d”,matrice[r][c]);
[/p]
[p]
printf(“\n”);
[/p]
[p]
}
[/p]
[p]
//deallocazione la matrice
[/p]
[p]
for(r=0; r<righe; r++)
[/p]
[p]
free(matrice[r]);
[/p]
[p]
free(matrice);
[/p]
[p]
getchar();
[/p]
[p]
return 0;
[/p]
[p]
}
[/p]
[p]
Domande da interrogazione
- How is memory allocated for a matrix in the provided code?
- What is the purpose of the nested loops in the code?
- How does the code ensure proper memory management after using the matrix?
Memory for the matrix is allocated using `malloc`, first for the rows with `matrice = (int **) malloc (righe*sizeof(int *));` and then for each row's columns within a loop.
The nested loops are used to input data into the matrix, where the outer loop iterates through the rows and the inner loop iterates through the columns, prompting the user for each element.
The code includes a deallocation step where it frees each row of the matrix with `free(matrice[r]);` and then frees the pointer to the matrix itself with `free(matrice);` to prevent memory leaks.