2017-04-08 73 views
-1

我一直通过在函数外部运行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

+3

1.了解指针和数组之间的区别。 2.不要在C++中使用malloc。 3.不要在C++中使用传递指针4.(高级)不要使用原始指针或C风格的数组 –

+0

感谢您的帮助。我知道我正在使用混合C和C++。我在做什么是有用的,因为我在学习。尽管如此,我仍然没有回答。 – Raydude

回答

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); 
} 
+0

很漂亮。非常感谢。 – Raydude

0

对于那些谁弄得像我,跟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]); 
    ... 
} 
... 

此操作,因为阵列由一个指针指向第一个元素通过。我确信自己需要将指针传递给指针,但这正是传递数组时传递的内容。