传递指向数组的指针数组,以便在malloc()发生的地方运行

时间:2017-04-08 23:47:48

标签: c++ arrays function pointers malloc

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

我拥有:uint8_t * jpg [6],这是六个指向六个jpg压缩图像的指针,这些图像将由读取文件的代码进行malloc编辑。换句话说,这是一个六个指针的数组,指向六个不确定大小的数组。

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

我尝试过很多东西,但却无法编译。

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

主要代码:

...
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

进行编译

2 个答案:

答案 0 :(得分:1)

在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);
}

答案 1 :(得分:0)

For those who are confused like I was, the right way to do it with C structures (in case you're using something antiquated like CudaC and don't want to spend all eternity converting C++ structures to C structures) is really pretty obvious and I feel pretty dumb for not realizing it until this morning.

main:

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

function:

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]);
  ...
}
...

This works because arrays are passed by a pointer to the first element. I had convinced myself that I needed to pass a pointer to the pointers, but that's exactly what gets passed when you pass an array.