hier j'avais posté une question: How should I pass a pointer to a function and allocate memory for the passed pointer from inside the called function?C Programmation: malloc() pour un tableau 2D (en utilisant le pointeur à pointeur)
A partir des réponses que j'ai, j'ai pu comprendre quelle erreur je faisais.
Je suis confronté à un nouveau problème maintenant, quelqu'un peut-il m'aider?
Je veux allouer dynamiquement un tableau 2D, donc je passe un pointeur à pointeur de mon main()
à une autre fonction appelée alloc_2D_pixels(...)
, où j'utilise malloc(...)
et for(...)
boucle pour allouer de la mémoire pour le tableau 2D.
Eh bien, après le retour de la fonction alloc_2D_pixels(...)
, le pointeur à pointeur NULL reste encore, si naturellement, lorsque je tente d'accéder ou essayer de free(...)
le pointeur à pointeur, le programme se bloque.
Quelqu'un peut-il me suggérer quelles erreurs je fais ici?
Aidez-moi !!!
Vikram
SOURCE:
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);
}
Salut Mark !!! :) Ouais, tu as raison, j'aurais dû poster un code de travail. Merci pour votre réponse détaillée, je l'apprécie. – HaggarTheHorrible