将指针数组传递给数组,以便在 malloc() 发生的位置发挥作用

Pass Array of pointers to arrays to function where malloc() will occur

本文关键字:数组 位置 作用 malloc 指针      更新时间:2023-10-16

我一直通过在函数外部运行 malloc(( 来避免这种情况,但实际上函数知道数组需要多大,而外部无法知道数组需要多大。

我有什么:uint8_t *jpg[6],这是六个指向六个 jpg 压缩图像的指针,这些图像将被文件中读取的代码错误定位。换句话说,这是一个由六个指针到六个不确定大小的数组的数组。

我一直在试图弄清楚如何将指向指针的指针传递到函数中,以便它可以 malloc(( 具有已知大小的 jpg 数据的内存。

我已经尝试了很多东西,但无法编译任何东西。

我的最新尝试看起来像这样,我不明白为什么它不起作用:

主代码:

...
uint8_t *jpg[6];
int size[6]; // returns the size of the images in bytes.
LoadJPG(&jpg, size);
...

功能:

LoadJPG(uint8_t ***jpg, int *size)
{
  ...
  *jpg = (uint8_t *) malloc(blahblahblah);
  ...
  memcpy(**jpg, *indata, blahblahblah);
  ...
}

错误指向函数调用和函数:

error: argument of type "uint8_t *(*)[6]" is incompatible with parameter of type "uint8_t ***"

我正在使用 gcc 4.9.4 进行编译

C++ 写入malloc'd空间而不在其中创建对象是未定义的行为。你提到你正在学习 - 一个好的学习方法是使用简单、惯用的C++代码。

该程序可能如下所示:

#include <array>
#include <vector>
void LoadJPG( std::array<std::vector<uint8_t>, 6> &jpgs )
{
    jpgs[0].resize(12345);
    // use std::copy or memcpy to copy into &jpgs[0][0]
    jpgs[1].resize(23456);
    // etc.
}
int main()
{
    std::array<std::vector<uint8_t>, 6> jpgs;
    LoadJPG(jpgs);
}

对于那些像我一样感到困惑的人来说,使用 C 结构的正确方法(如果您使用的是像 CudaC 这样过时的东西并且不想花费所有时间将C++结构转换为 C 结构(真的非常明显,直到今天早上才意识到这一点,我感到很愚蠢。

主要:

uint8_t *jpg[CAMERAS];
int size[CAMERAS];
GetRawImagesFromCamera(jpg, size);
...
free(jpg[]);

功能:

void GetRawImagesFromCamera(uint8_t **jpg, int *size)
...
for (i=0; i < CAMERAS; i++)
{
  jpg[i] = (uint8_t *) malloc(size[i]);
  memcpy((void *) jpg[i], (void *) buff[i], size[i]);
  ...
}
...

这是有效的,因为数组是通过指向第一个元素的指针传递的。我已经说服自己,我需要传递指向指针的指针,但这正是传递数组时传递的内容。