gestern habe ich eine Frage gestellt hatte: How should I pass a pointer to a function and allocate memory for the passed pointer from inside the called function?C-Programmierung: malloc() für ein 2D-Array (mit Pointer-to-Zeiger)
Aus den Antworten, die ich bekam, konnte ich verstehen, welche Fehler ich tat.
Ich stehe jetzt vor einem neuen Problem, kann mir jemand dabei helfen?
Ich möchte ein 2D-Array dynamisch zuzuweisen, so bin ich vorbei einen Pointer-to-Pointer von meinem main()
auf eine andere Funktion alloc_2D_pixels(...)
genannt, wo ich malloc(...)
und for(...)
Schleife verwenden, um Speicher für das 2D-Array zuzuordnen.
Nun, nach der Rückkehr von der -Funktion bleibt der Zeiger-Zeiger immer noch NULL, so natürlich, wenn ich versuche, auf den Zeiger-zu-Zeiger zuzugreifen oder versuchen, free(...)
, hängt das Programm.
Kann mir jemand vorschlagen, welche Fehler ich hier mache?
Hilfe !!!
Vikram
QUELLE:
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 !!! :) Ja, du hast recht, ich hätte einen funktionierenden Code schreiben sollen. Danke für Ihre ausführliche Antwort, ich weiß es zu schätzen. – HaggarTheHorrible