将指针数组传递给数组,以便在 malloc() 发生的位置发挥作用
Pass Array of pointers to arrays to function where malloc() will occur
我一直通过在函数外部运行 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]);
...
}
...
这是有效的,因为数组是通过指向第一个元素的指针传递的。我已经说服自己,我需要传递指向指针的指针,但这正是传递数组时传递的内容。
相关文章:
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 如何在数组中交换最小和最大的位置?
- C++ 2D 数组写入多个位置
- C++指针数组到字符数组中的特定位置
- 递增 'int i = 0' 以在初始化的字符数组的位置递增
- 数组中所有元素的最新最小元素的第五个位置
- 关于引用数组位置的问题
- 在给定元素在螺旋上的位置的情况下,在二维数组中查找元素
- 创建 2D 数组0xCCCCCCCC访问冲突写入位置
- 如何计算 3d 数组中的索引值在内存中的位置?如何计算字符**中的索引值在内存中的位置?
- 如何在 3x4 数组中随机 4 个不同的位置
- C++不同内存位置中的默认数组值
- 使用动态数组访问冲突写入位置
- 将字符串分配到动态数组位置时出错
- 查找数组位置的最大值
- 如何使用变量名称引用数组位置
- 面向对象C++帮助?出于某种原因,对象变量的输出返回数值数组位置而不是实际值
- 在 C++/CLI Visual Studio C++ 中以指定的数组位置将文本框中的值保存在 char 中
- 将名称添加到C++中的数组位置
- 如何在c++中表示数组位置的范围