ieri avevo postato una domanda: How should I pass a pointer to a function and allocate memory for the passed pointer from inside the called function?programmazione C: malloc() per una matrice 2D (con puntatore a puntatore)
Dalle risposte che ho ricevuto, sono stato in grado di capire che cosa errore che stavo facendo.
Sto affrontando un nuovo problema ora, qualcuno può aiutare con questo?
voglio allocare dinamicamente una matrice 2D, quindi sto passando un puntatore a puntatore dal mio main()
ad un'altra funzione chiamata alloc_2D_pixels(...)
, dove io uso malloc(...)
e for(...)
ciclo per allocare memoria per la matrice 2D.
Ebbene, dopo il ritorno dalla funzione alloc_2D_pixels(...)
, il puntatore puntatore a NULL rimane ancora, così naturalmente, quando provo l'accesso o cercare di free(...)
il puntatore-a-Pointer, il programma si blocca.
Qualcuno può suggerirmi quali errori sto facendo qui?
Aiuto !!!
Vikram
FONTE:
main()
{
unsigned char **ptr;
unsigned int rows, cols;
if(alloc_2D_pixels(&ptr, rows, cols)==ERROR) // Satisfies this condition
printf("Memory for the 2D array not allocated"); // NO ERROR is returned
if(ptr == NULL) // ptr is NULL so no memory was allocated
printf("Yes its NULL!");
// Because ptr is NULL, with any of these 3 statements below the program HANGS
ptr[0][0] = 10;
printf("Element: %d",ptr[0][0]);
free_2D_alloc(&ptr);
}
signed char alloc_2D_pixels(unsigned char ***memory, unsigned int rows, unsigned int cols)
{
signed char status = NO_ERROR;
memory = malloc(rows * sizeof(unsigned char**));
if(memory == NULL)
{
status = ERROR;
printf("ERROR: Memory allocation failed!");
}
else
{
int i;
for(i = 0; i< cols; i++)
{
memory[i] = malloc(cols * sizeof(unsigned char));
if(memory[i]==NULL)
{
status = ERROR;
printf("ERROR: Memory allocation failed!");
}
}
}
// Inserted the statements below for debug purpose only
memory[0][0] = (unsigned char)10; // I'm able to access the array from
printf("\nElement %d",memory[0][0]); // here with no problems
return status;
}
void free_2D_pixels(unsigned char ***ptr, unsigned int rows)
{
int i;
for(i = 0; i < rows; i++)
{
free(ptr[i]);
}
free(ptr);
}
Hey Mark !!! :) Sì, hai ragione, avrei dovuto pubblicare un codice funzionante. Grazie per la tua risposta dettagliata, lo apprezzo. – HaggarTheHorrible