I am trying to allocate memory to a struct function. However, I am not sure how to do it in 2D arrays. The question asks me to allocate memory to initialized rows and columns and if successful, it should return a pointer to a newly-allocated pointer, otherwise return NULL.
typedef struct
{
uint8_t** pixels;
unsigned int rows;
unsigned int cols;
} img_t;
/* A type for returning status codes */
typedef enum
{
IMG_OK,
IMG_BADINPUT,
IMG_BADARRAY,
IMG_BADCOL,
IMG_BADROW,
IMG_NOTFOUND
} img_result_t;
/* task 01 */
// Create a new img_t with initial size rows and cols. If successful
// (i.e. memory allocation succeeds), returns a pointer to a
// newly-allocated img_t. If unsuccessful, returns a null pointer.
img_t* img_create(unsigned int rows, unsigned int cols)
{
img_t.rows = 640;
img_t.cols = 480;
double **A = malloc(img_t.rows * sizeof(double*));
for(int i = 0; i < img_t.rows; i++)
{
A[i] = malloc(img_t.cols * sizeof(double));
}
// How do I check whether or not the memory has been assigned or not
//as the question demands?
}
INPUT: the number of rows and cols of the desired array. OUTPUT: img_create() returns the POINTER to a new instance of data structure img_t. You may initialize the values in your pixels to 0. BEHAVIOUR: if malloc() fails (i.e. returns NULL), img_create() returns NULL
Can someone help me with it?