获取所有值三重指针C ++

问题描述 投票:0回答:2

我有一个外部C-DLL,我在我的C ++项目中使用它。我坚持的功能是Get_ALLFiles(char*** listOfFiles, int* nbrOfFiles)。此函数在文件夹上应用某些条件并返回与条件匹配的文件。

int nbrOfFiles= 0;
//just get the number of files 
Get_ALLFiles((char***)malloc(1 * sizeof(char***)), &ElementNbr);

// pointer allocation 
char ***MyFilesList = (char***)malloc(nbrOfFiles* sizeof(char**));
for (int i = 0; i < ElementNbr; i++) {
    MyFilesList [i] = (char**)malloc(ElementNbr * 32 * sizeof(char*));
    for (int j = 0; j < 32; j++)
        MyFilesList [i][j] = (char*)malloc(ElementNbr * sizeof(char));
}

//Now i will use the function in order to get all the files (in my exemple 
//I have 10 which respond the criteria 
Get_ALLFiles(MyFilesList , &nbrOfFiles);

在我的“MyFilesList”中,我只有第一个元素,如何获取“MyFilesList”中的所有元素?

c++ pointers dll
2个回答
0
投票

我的猜测是函数本身分配内存,你应该将指针传递给接收值的变量。在C中模拟传递引用

就像是

char** MyFilesList;
int NumberFiles;

// Get a list of all files
Get_ALLFiles(&MyFilesList, &NumberFiles);

// Print all files
for (int i = 0; i < NumberFiles; ++i)
{
    std::cout << "File #" i + 1 << " is " << MyFilesList[i] << '\n';
}

// Free the memory
for (int i = 0; i < NumberFiles; ++i)
{
    free(MyFilesList[i]);
}
free(MyFilesList);

0
投票

您应该将变量的地址传递给函数,而不是指向动态内存的指针。 也就是说,就像你对数字一样。

然后,该函数将分配所有内存并通过收到的指针更新变量。

像这样:

char** MyFilesList = nullptr;
int nbrOfFiles = 0;
Get_ALLFiles(&MyFilesList , &nbrOfFiles);
© www.soinside.com 2019 - 2024. All rights reserved.