【发布时间】:2021-07-18 20:55:46
【问题描述】:
我必须创建一个新的img_t,其中包含初始大小的行和列。如果成功(内存分配成功),则返回一个指向新分配的img_t的指针。
我无法初始化行和列。
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;
//something is wrong in this constructor*******
img_t* img_create(unsigned int rows, unsigned int cols){
img_t **arr = malloc(rows * sizeof(img_t*));
for(int i = 0; i < rows; i++){
arr[i] = malloc(cols * sizeof(img_t));
arr[i]->rows = rows;
return arr[i];
}
return 0;
}
// helper function that prints the content of the img
void print_img(img_t* im) {
if (im == NULL) {
printf("Invalid img (null).\n");
return;
}
printf("Printing img of row length %d and col length %d:\n", im->rows, im->cols);
for (unsigned int i=0; i<im->rows; i++) {
for (unsigned int j=0; j<im->cols; j++) {
printf("%d ", im->pixels[i][j]);
}
printf("\n");
}
printf("\n");
}
int main() {
// test variables to hold values returned by the functions
img_t* test_im = NULL;
img_result_t test_result = IMG_OK;
// test task 01 & 02
printf("Creating test_im by calling 'img_create(10, 10)'\n");
test_im = img_create(10, 10);
if (test_im == NULL) {
printf("test_im == NULL\n");
return 1; //exit with a non-zero value
}
printf("test_im\n");
printf("Printing test_im\n");
print_img(test_im);
}
程序输出:
test_im
Printing test_im
Printing img of row length 10 and col length 0:
【问题讨论】:
-
return arr[i];你明白return会立即终止函数吗?这意味着for循环只运行一次。此外,很明显,您要为像素字段而不是整个img_t创建一个二维数组。
标签: c multidimensional-array heap-memory