어제의 malloc() : 내가 가진 답변에서 How should I pass a pointer to a function and allocate memory for the passed pointer from inside the called function?C 프로그래밍 : (포인터에 대한 포인터를 사용하여) 2 차원 배열 내가 질문을 게시했다
, 나는 내가 무엇을하고 있었는지 실수를 이해 할 수 있었다.
지금 새로운 문제에 직면하고 있습니다. 아무도 도와 드릴 수 있습니까?
나는 그래서 내가 2D 배열을위한 메모리를 할당 할malloc(...)
및
for(...)
루프를 사용
alloc_2D_pixels(...)
라는 또 다른 기능, 내
main()
에서 포인터 - 투 - 포인터를 전달하고있어, 동적 2 차원 배열을 할당 할.
글쎄, alloc_2D_pixels(...)
함수에서 돌아온 후에 포인터 포인터는 여전히 NULL로 남아 있으므로 포인터를 포인터로 free(...)
에 액세스하거나 시도하면 자연히 프로그램이 중단됩니다.
누구든지 내가 여기서 무슨 실수를 저에게 제안 할 수 있습니까?
도움말 !!!
크람
SOURCE : memory
에 액세스 할 때 당신의 alloc_2D_pixels
기능에
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);
}
안녕 마크! :) 그래, 네가 맞아 내가 제대로 작동하는 코드를 게시 했어야했다. 귀하의 자세한 답변을 주셔서 감사합니다, 나는 그것을 주셔서 감사합니다. – HaggarTheHorrible