C编程:用于2D数组的malloc()(使用指针到指针)

C编程:用于2D数组的malloc()(使用指针到指针),c,pointers,malloc,multidimensional-array,C,Pointers,Malloc,Multidimensional Array,昨天我发布了一个问题: 从我得到的答案中,我能够理解我犯了什么错误 我现在面临一个新问题,有人能帮我解决吗 我想动态分配一个2D数组,所以我将一个指向指针的指针从我的main()传递给另一个名为alloc\u 2D\u pixels(…),其中我使用malloc(…)和for(…)循环为2D数组分配内存 嗯,从alloc\u 2D\u pixels(…)函数返回后,指针指针仍然保持为空,因此,当我尝试访问或尝试释放(…)指针指针时,程序自然挂起 有人能告诉我我在这里犯了什么错误吗 救命啊 维克拉

昨天我发布了一个问题:

从我得到的答案中,我能够理解我犯了什么错误

我现在面临一个新问题,有人能帮我解决吗

我想动态分配一个2D数组,所以我将一个指向指针的指针从我的
main()
传递给另一个名为
alloc\u 2D\u pixels(…)
,其中我使用
malloc(…)
for(…)
循环为2D数组分配内存

嗯,从
alloc\u 2D\u 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);
}
main()
{
无符号字符**ptr;
无符号整数行,cols;
如果(alloc_2D_像素(&ptr,rows,cols)=ERROR)//满足此条件
printf(“未分配2D数组的内存”);//不返回任何错误
if(ptr==NULL)//ptr为NULL,因此未分配内存
printf(“是的,它是空的!”);
//因为ptr为NULL,下面的3条语句中的任何一条都会挂起程序
ptr[0][0]=10;
printf(“元素:%d”,ptr[0][0]);
自由分配(ptr);
}
有符号字符alloc_2D_像素(无符号字符***内存、无符号整数行、无符号整数列)
{
签名字符状态=无错误;
内存=malloc(行*sizeof(无符号字符**));
if(内存==NULL)
{
状态=错误;
printf(“错误:内存分配失败!”);
}
其他的
{
int i;
对于(i=0;i
alloc\u 2D\u pixels
功能中,访问
内存时需要另一个间接级别。现在,只修改参数,而不修改参数指向的指针。比如说,

memory = malloc(rows * sizeof(unsigned char** ));
// becomes
*memory = malloc(rows * sizeof(unsigned char** ));

// and later...
memory[i] = malloc(cols * sizeof(unsigned char));
// becomes
(*memory)[i] = malloc(cols * sizeof(unsigned char));

(基本上,无论您在哪里使用
内存
,都需要使用
(*内存)
;只有在使用下标以确保按正确顺序应用运算符时才需要括号)

它看起来也像,您正在使用未初始化的
变量

一个错误是发布无法编译的代码:)。下面是我在
/*此样式*/:

/* Next four lines get your code to compile */
#include <stdio.h>
#include <stdlib.h>
#define NO_ERROR 0
#define ERROR    1

/* prototypes for functions used by main but declared after main
   (or move main to the end of the file */
signed char alloc_2D_pixels(unsigned char*** memory, unsigned int rows, unsigned int cols);
void free_2D_pixels(unsigned char** ptr, unsigned int rows);

/* main should return int */
int main()
{
    unsigned char** ptr;
    /* need to define rows and cols with an actual value */
    unsigned int rows = 5, cols = 5;

    if(alloc_2D_pixels(&ptr, rows, cols) == ERROR)    // Satisfies this condition
        printf("Memory for the 2D array not allocated"); // ERROR is returned

    if(ptr == NULL)                    // ptr is NULL so no memory was allocated
        printf("Yes its NULL!");
    else
    {
        /* Added else clause so below code only runs if allocation worked. */
        /* Added code to write to every element as a test. */
        unsigned int row,col;
        for(row = 0; row < rows; row++)
            for(col = 0; col < cols; col++)
                ptr[0][0] = (unsigned char)(row + col);

           /* no need for &ptr here, not returning anything so no need to pass
              by reference */
           free_2D_pixels(ptr, rows);
    }

    return 0;
}

signed char alloc_2D_pixels(unsigned char*** memory, unsigned int rows, unsigned int cols)
{
    signed char status = NO_ERROR;

    /* In case we fail the returned memory ptr will be initialized */
    *memory = NULL;

    /* defining a temp ptr, otherwise would have to use (*memory) everywhere
       ptr is used (yuck) */
    unsigned char** ptr;

    /* Each row should only contain an unsigned char*, not an unsigned
       char**, because each row will be an array of unsigned char */
    ptr = malloc(rows * sizeof(unsigned char*));

    if(ptr == NULL)
    {
        status = ERROR;
        printf("ERROR: Memory allocation failed!");
    }
    else
    {
        /* rows/cols are unsigned, so this should be too */
        unsigned int i;

        /* had an error here.  alloced rows above so iterate through rows
           not cols here */
        for(i = 0; i < rows; i++)
        {
            ptr[i] = malloc(cols * sizeof(unsigned char));

            if(ptr[i] == NULL)
            {
                status = ERROR;
                printf("ERROR: Memory allocation failed!");
                /* still a problem here, if exiting with error,
                   should free any column mallocs that were
                   successful. */
            }
        }
    }

    /* it worked so return ptr */
    *memory = ptr;
    return status;
}


/* no need for *** here. Not modifying and returning ptr */
/* it also was a bug...would've needed (*ptr) everywhere below */
void free_2D_pixels(unsigned char** ptr, unsigned int rows)
{
    /* should be unsigned like rows */
    unsigned int i;

    for(i = 0; i < rows; i++)
    {
        free(ptr[i]);
    }

    free(ptr);
}
/*接下来的四行是要编译的代码*/
#包括
#包括
#定义无错误0
#定义错误1
/*main使用但在main之后声明的函数的原型
(或将main移到文件末尾*/
有符号字符alloc_2D_像素(无符号字符***内存、无符号整数行、无符号整数列);
无效的2D像素(无符号字符**ptr,无符号整数行);
/*main应该返回int*/
int main()
{
无符号字符**ptr;
/*需要使用实际值定义行和列*/
无符号整数行=5,cols=5;
如果(alloc_2D_像素(&ptr,rows,cols)=ERROR)//满足此条件
printf(“未分配2D数组的内存”);//返回错误
if(ptr==NULL)//ptr为NULL,因此未分配内存
printf(“是的,它是空的!”);
其他的
{
/*添加了else子句,使下面的代码仅在分配有效时运行*/
/*添加了作为测试写入每个元素的代码*/
无符号整数行,列;
对于(行=0;行<行;行++)
for(col=0;colsigned char alloc_2D_pixels(unsigned char*** memory,
                            unsigned int rows,
                            unsigned int cols)
{
    int colspan = cols * sizeof(char);
    int rowspan = rows * sizeof(char*);
    unsigned char **rowptrs = *memory = malloc(rowspan + rows * colspan));

    /* malloc failure handling left to the reader */

    unsigned char *payload = ((unsigned char *)rowptrs) + rowspan;
    int i;
    for (i = 0; i < rows; payload += colspan, i++)
        rowptrs[i] = payload;
}