简体   繁体   中英

Pointer to pointer in parameter in C

I need to make a array of strings (dynamic). I send a pointer to pointer to function, But in the function I got error.

This is the function:

void CheckFilesInFolder(char* pathOfFolder, char*** namesFiles);

I call to function like that:

char** namesFiles = NULL;
CheckFilesInFolder("Debug", &namesFiles);

And in the function i do that malloc, and when I = 1 its break.

*namesFiles = (char**)malloc(*namesFiles, 10 * sizeof(char*) );
int i = 0;
for (i = 0; i < 10; i++)
{
    *(namesFiles[i]) = (char*)malloc(MAX_FILE_NAME);
}

malloc only takes 1 size_t argument. Change this:

*namesFiles = (char**)malloc(*namesFiles, 10 * sizeof(char*) );

to this:

*namesFiles = (char**)malloc(10 * sizeof(char*) );

Let me know of any other errors that might occur.

Also, if you need to pass the pointer to the caller, why don't you return it instead of getting it by passing the pointer's adress as an argument?

Like so: char** CheckFilesInFolder(char* pathOfFolder);

and in the function do something like:

char** namesFiles = (char**)malloc(10 * sizeof(char*) );
//(...)
return namesFiles;

To call, just do this: char** namesFiles = CheckFilesInFolder("Debug");

I believe this is the best way.

EDIT 1.0 To reply to the comment from "alk", here is the way of solving this problem with a pointer to an array of char* through the arguments instead of my (simpler) suggestion to return a char**:

Call the function like this:

char** namesFiles;
CheckFilesInFolder("Debug", &namesFiles);

Inside the function:

*namesFiles = (char**)malloc(10 * sizeof(char*));
int i;
for (i = 0; i < 10; i++)
    (*namesFiles)[i] = (char*)malloc(MAX_FILE_NAME);

Function declaration:

void CheckFilesInFolder(char* pathOfFolder, char*** namesFiles);

Use this is you really need to do this using arguments for example if you want to call this function as the routine of a pthread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM