C 编程:用于二维数组的 malloc()(使用指针到指针) [英] C Programming: malloc() for a 2D array (using pointer-to-pointer)

查看:26
本文介绍了C 编程:用于二维数组的 malloc()(使用指针到指针)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

昨天我发布了一个问题:我应该如何传递一个指向函数的指针以及从被调用函数内部为传递的指针分配内存?

yesterday I had posted a question: How should I pass a pointer to a function and allocate memory for the passed pointer from inside the called function?

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

From the answers I got, I was able to understand what mistake I was doing.

我现在面临一个新问题,有人可以帮忙吗?

I'm facing a new problem now, can anyone help out with this?

我想动态分配一个二维数组,所以我将一个指针到指针从我的 main() 传递给另一个名为 alloc_2D_pixels(...) 的函数code>,我使用 malloc(...)for(...) 循环为二维数组分配内存.

I want to dynamically allocate a 2D array, so I'm passing a Pointer-to-Pointer from my main() to another function called alloc_2D_pixels(...), where I use malloc(...) and for(...) loop to allocate memory for the 2D array.

好吧,从 alloc_2D_pixels(...) 函数返回后,指向指针的指针仍然保持为 NULL,所以很自然地,当我尝试访问或尝试 free(...) Pointer-to-Pointer,程序挂起.

Well, after returning from the alloc_2D_pixels(...) function, the pointer-to-pointer still remains NULL, so naturally, when I try accessing or try to free(...) the Pointer-to-Pointer, the program hangs.

谁能告诉我我在这里犯了什么错误?

Can anyone suggest me what mistakes I'm doing here?

帮助!!!

维克拉姆

来源:

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("
Element %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);
}

推荐答案

一个错误是发布了无法编译的代码:).以下是更正后的代码,其中包含我的评论
/* 这种风格 */:

One mistake is posting code that won't compile :). Below is corrected code with my comments in
/* this style */:

/* 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);
}

这篇关于C 编程:用于二维数组的 malloc()(使用指针到指针)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆