ngày hôm qua tôi đã đăng một câu hỏi: How should I pass a pointer to a function and allocate memory for the passed pointer from inside the called function?C Programming: malloc() cho một mảng 2D (sử dụng con trỏ-to-pointer)
Từ câu trả lời tôi nhận được, tôi đã có thể hiểu những gì sai lầm tôi đang làm.
Tôi đang gặp phải sự cố mới ngay bây giờ, bất kỳ ai có thể trợ giúp về vấn đề này không?
tôi muốn tự động phân bổ một mảng 2D, vì vậy tôi đi qua một con trỏ-to-Pointer từ main()
tôi đến một chức năng gọi là alloc_2D_pixels(...)
, nơi tôi sử dụng malloc(...)
và for(...)
vòng lặp để cấp phát bộ nhớ cho mảng 2D.
Vâng, sau khi trở về từ hàm alloc_2D_pixels(...)
, con trỏ trỏ đến vẫn còn NULL, vì vậy tự nhiên, khi tôi thử truy cập hoặc thử free(...)
Con trỏ trỏ đến, chương trình bị treo.
Có ai có thể gợi ý cho tôi những sai lầm tôi đang làm ở đây không?
Trợ giúp !!!
Vikram
NGUỒN:
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 !!! :) Yeah, bạn nói đúng tôi nên đã đăng một mã số làm việc. Cảm ơn bạn đã trả lời chi tiết của bạn, tôi đánh giá cao nó. – HaggarTheHorrible